const delay = function (time) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(time);
resolve(time)
}, time);
})
}
let tasks = [
() => delay(1001),
() => delay(1002),
() => delay(1005),
() => delay(1004),
() => delay(1007),
() => delay(1003),
() => delay(1008)
]
// Promise.all(tasks.map(item => item())).then(res => {
// console.log(res);
// })
// function createRequest(tasks, limit = 3) {
// let index = 0,
// results = [],// 存放结果
// together = new Array(limit).fill(null);//创建工作区
// together = together.map(_ => {
// return new Promise((resolve, reject) => {
// const fun = function () {
// if (index >= tasks.length) {
// resolve(results)
// return
// }
// let oldIndex = index
// const task = tasks[index++]
// task().then(res => {
// results[oldIndex] = res
// fun()
// }).catch(reason => reject(reason))
// }
// fun()
// })
// })
// return Promise.all(together).then(() => results, reason => Promise.reject(reason))
// }
// createRequest(tasks, 2).then(res => {
// console.log(res);
// }).catch(reason => {
// console.log(reason);
// })
function createRequest(tasks, limit, cb) {
class TaskQueue {
// 执行中的任务个数
running = 0;
// 存放任务的工作区
queue = [];
// 存放结果
results = []
pushTask(task) {
let self = this
self.queue.push(task)
self.next()
}
next() {
let self = this
// 执行中任务个数小于并发数量并且工作区有值继续拿任务执行
while (self.running < limit && self.queue.length) {
self.running++
let task = self.queue.shift()
task().then(res => {
self.results.push(res)
}).finally(() => {
// 不论失败成功继续拿任务执行
self.running--
self.next()
})
}
// 执行中任务个数=0结束
if (self.running === 0) {
cb(self.results)
}
}
}
let tq = new TaskQueue()
tasks.forEach(task => tq.pushTask(task))
}
createRequest(tasks, 3, results => {
console.log(results);
})