<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
(()=> {
// 创建异步任务
function createAsyncTask(delay, index) {
return () => new Promise((resolve) => {
console.log(`Task event is ${index}, ${delay}s`);
return setTimeout(() => resolve(), delay * 1000)
})
}
// 批量创建异步任务
const tasks = [3,6,2,4,2,6,3,7,3].map((t,i)=> createAsyncTask(t,i))
// 实现 一个方法, 最大并发数, 一个任务完成, 另外一个任务补进去,但是不能超过limit
async function runTask(taskList, limit = 8) {
let startTime = Date.now()
let runningTasks = []
for (let i = 0; i < taskList.length; i++) {
const task = taskList[i];
// 执行任务
const t = task().then(res=> {
runningTasks = runningTasks.filter(c=> c!== t) // 用 === 表示当前任务
return res
})
runningTasks.push(t)
// 开始执行任务
if(runningTasks.length >= limit) {
await Promise.race(runningTasks)
}
}
// 等待所有任务执行完
console.info(1, runningTasks)
await Promise.all(runningTasks)
return Date.now() - startTime
}
runTask(tasks).then(res=> console.info('共花了多少时间', res))
})()
</script>
</body>
</html>
js 异步任务 并发 如何实现?
于 2024-08-26 20:36:34 首次发布