我正在撰寫一個函式,它應該盡可能快地執行所有的異步函式,但是,只有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)。
}
//下面的代碼只是為了測驗。
const asyncFuncLong = (/span>) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve()。
}, 6000)。)
});
};
const asyncFuncShort = (/span>) => {
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)。
});
編輯:修正。現在一切正常了。謝謝你們兩個!
uj5u.com熱心網友回復:
fns陣列是一個函式的串列。這些函式回傳Promise物件。然后您將該函式串列傳遞給您的runPromises函式,該函式似乎想接收一個Promise物件的串列作為引數。但是你正在傳遞給它一個函式的串列。
我的建議是
改變
runPromises函式,使其在某一時刻實際呼叫prom()(或者只是使用一個映射,如const r = await Promise.all(queue.map((fn) => { return fn(); }));),或者將
fns的定義改為let fns = [ asyncFuncLong(), asyncFuncShort(), asyncFuncLong(), ... ] ;.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/318017.html
標籤:
