我正在寻找一个Promise函数包装器,它可以在给定的Promise运行时限制/节流,以便在给定的时间只运行一定数量的Promise。
在下面的情况下delayPromise
,永远不应该同时运行,它们都应该按照先到先得的顺序一次运行一个。
import Promise from 'bluebird'
function _delayPromise (seconds, str) {
console.log(str)
return Promise.delay(seconds)
}
let delayPromise = limitConcurrency(_delayPromise, 1)
async function a() {
await delayPromise(100, "a:a")
await delayPromise(100, "a:b")
await delayPromise(100, "a:c")
}
async function b() {
await delayPromise(100, "b:a")
await delayPromise(100, "b:b")
await delayPromise(100, "b:c")
}
a().then(() => console.log('done'))
b().then(() => console.log('done'))
关于如何设置这样的队列的任何想法?
我有一个来自精彩的“去抖动”功能Benjamin Gruenbaum
。我需要修改它以根据它自己的执行而不是延迟来限制Promise。
export function promiseDebounce (fn, delay, count) {
let working = 0
let queue = []
function work () {
if ((queue.length === 0) || (working === count)) return
working++
Promise.delay(delay).tap(function () { working-- }).then(work)
var next = queue.shift()
next[2](fn.apply(next[0], next[1]))
}
return function debounced () {
var args = arguments
return new Promise(function (resolve) {
queue.push([this, args, resolve])
if (working < count) work()
}.bind(this))
}
}