并发执行任务的JS代码
async function uploadFile(file) { const formData = new FormData(); formData.append('video', file); try { const response = await fetch('YOUR_UPLOAD_URL', { method: 'POST', body: formData, }); if (!response.ok) { throw new Error(`Upload failed: ${response.statusText}`); } const result = await response.json(); console.log('Upload successful:', result); } catch (error) { console.error('Error uploading file:', error); } } async function uploadFiles(files, concurrencyLimit) { const uploadQueue = []; const results = []; for (const file of files) { const uploadPromise = uploadFile(file).then(result => { results.push(result); }); uploadQueue.push(uploadPromise); // 控制并发数 if (uploadQueue.length >= concurrencyLimit) { await Promise.race(uploadQueue); // 等待最先完成的上传 uploadQueue.splice(uploadQueue.findIndex(p => p === uploadPromise), 1); // 移除已完成的上传 } } // 等待所有剩余的上传完成 await Promise.all(uploadQueue); return results; } // 使用示例 const fileInput = document.getElementById('fileInput'); const uploadButton = document.getElementById('uploadButton'); uploadButton.addEventListener('click', () => { const files = Array.from(fileInput.files); const concurrencyLimit = 3; // 设置并发数 uploadFiles(files, concurrencyLimit) .then(results => { console.log('All uploads completed:', results); }) .catch(error => { console.error('Error during uploads:', error); }); });
如并发上传就是一个并发任务的例子,具体参考:
https://juejin.cn/post/6968714492137979940
积累小的知识,才能成就大的智慧,希望网上少一些复制多一些原创有用的答案