gpt4 book ai didi

javascript - 为什么执行不会在 await (async/await JS) 处停止?

转载 作者:行者123 更新时间:2023-12-04 17:12:23 29 4
gpt4 key购买 nike

我正在编写一个应该尽可能快地执行所有异步函数的函数,但是,它们中只有 5 个可以同时运行。

我想使用 Promise.race 来实现,所以实现不是最好的。问题是代码执行不会在 await 处停止。我希望 counter 变量只有在 promise 解决时才会递减,但它不会等待 promise 解决。代码不会在 Promise.all 处停止,这让我觉得我对 promises 的理解不正确。代码如下,所讨论的函数是 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);
});


编辑:固定。现在一切正常。谢谢你们!

最佳答案

fns 数组是一个函数列表。这些函数返回 Promise 对象。然后将该函数列表传递给 runPromises 函数,该函数似乎想要将 Promise 对象列表作为参数。但是您向它传递了一个函数列表。

我的建议是

  • 更改 runPromises 函数,使其在某个时刻实际调用 prom()(或者只使用映射,如 const r = await Promise.all(queue.map((fn) => { return fn(); }));), 或者

  • fns 的定义更改为类似 let fns = [asyncFuncLong(), asyncFuncShort(), asyncFuncLong(), ... ];

关于javascript - 为什么执行不会在 await (async/await JS) 处停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69212353/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com