// 并发数量计数
let count = 0
function run () {
if (count < 3 && list.length) {
count+=1
get(list.shift()).then(() => {
count-=1
run()
})
}
}
// 限定三个并发数量
run()
run()
run()
class Limit {
constructor (n) {
this.limit = n
this.count = 0
this.queue = []
}
enqueue (fn) {
// 关键代码: fn, resolve, reject 统一管理
return new Promise((resolve, reject) => {
this.queue.push({ fn, resolve, reject })
})
}
dequeue () {
if (this.count < this.limit && this.queue.length) {
// 等到 Promise 计数器小于阈值时,则出队执行
const { fn, resolve, reject } = this.queue.shift()
this.run(fn).then(resolve).catch(reject)
}
}
// async/await 简化错误处理
async run (fn) {
this.count++
// 维护一个计数器
const value = await fn()
this.count--
// 执行完,看看队列有东西没
this.dequeue()
return value
}
build (fn) {
if (this.count < this.limit) {
// 如果没有到达阈值,直接执行
return this.run(fn)
} else {
// 如果超出阈值,则先扔到队列中,等待有空闲时执行
return this.enqueue(fn)
}
}
}
Promise.map = function (list, fn, { concurrency }) {
const limit = new Limit(concurrency)
return Promise.all(list.map((...args) => {
return limit.build(() => fn(...args))
}))
}
如何实现 promise.map,并限制并发数
并发控制与异步任务调度:实现高效并发限制
最新推荐文章于 2024-10-16 07:00:00 发布
本文介绍了一种并发数量限制的方法,通过`run`函数和`Limit`类来确保不超过3个任务同时执行。利用Promise和队列管理,简化了错误处理并优化了资源使用。核心在于`Limit`类的构造、enqueue、dequeue和run方法,它们共同实现了并发任务的控制。
417

被折叠的 条评论
为什么被折叠?



