我正在编写一个函数,它应该尽可能快地执行所有异步函数,但是,其中只有5个可以同时运行。
我想使用Promise.race
来实现它,所以实现不是最好的。问题是,代码的执行并不会在await
停止。我预计,只有在承诺得到解决时,counter
变量才会减少,但它不会等待承诺的解决。代码也不会停止在Promise.all
,这使我觉得我对承诺的理解是不恰当的。代码在下面,所讨论的函数是runPromises
。
async function runPromises(promises, limit) {
const LIMIT = limit || 10;
let promsCopy = promises.slice();
let counter = 0;
let queue = [];
while (promsCopy.length !== 0) {
if (counter < LIMIT) {
let prom = promsCopy.shift();
if (prom) {
queue.push(prom());
counter += 1;
if (counter >= LIMIT) {
let [completed] = await Promise.race(
queue.map((p) => p.then((_) => [p]))
);
queue.splice(queue.indexOf(completed), 1);
counter -= 1;
}
}
}
}
await Promise.all(queue);
}
// the code below is just for testing
const asyncFuncLong = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 6000);
});
};
const asyncFuncShort = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 1000);
});
};
let fns = [
asyncFuncLong,
asyncFuncLong,
asyncFuncLong,
asyncFuncLong,
asyncFuncLong,
asyncFuncLong,
asyncFuncLong,
asyncFuncLong,
asyncFuncLong,
asyncFuncLong,
asyncFuncLong,
asyncFuncLong,
asyncFuncLong,
asyncFuncLong,
asyncFuncLong,
asyncFuncLong,
];
let start = Date.now();
runPromises(fns, 10).then(() => {
console.log(Date.now() - start);
});
编辑:修正。现在一切都正常了。谢谢你们俩!
发布于 2021-09-16 10:40:41
fns
数组是一个函数列表。这些函数返回Promise
对象。然后将该函数列表传递给您的runPromises
函数,该函数似乎希望将Promise
对象的列表作为参数。但是您要传递给它一个函数列表。
我的建议是
runPromises
函数,以便它在某一点上实际调用prom()
(或者只使用地图,如const r = await Promise.all(queue.map((fn) => { return fn(); }));
)或let fns = [ asyncFuncLong(), asyncFuncShort(), asyncFuncLong(), ... ];
.
fns
的定义更改为类似于https://stackoverflow.com/questions/69212353
复制