gpt4 book ai didi

javascript - 等待promise for循环

转载 作者:行者123 更新时间:2023-12-03 13:23:45 25 4
gpt4 key购买 nike

let currentProduct;

for (let i = 0; i < products.length; i++) {
currentProduct = products[i];

subscription.getAll(products[i]._id)
.then((subs) => {
update(subs, currentProduct);
});
}

我使用的是bluebird,方法 getAll 更新返回 promise 。我如何说“等到两个 promise 返回,然后更新currentProduct值”?我对JS很陌生...

最佳答案

如果可以使用async/await,这将很简单:

// Make sure that this code is inside a function declared using
// the `async` keyword.
let currentProduct;

for (let i = 0; i < products.length; i++) {
currentProduct = products[i];

// By using await, the code will halt here until
// the promise resolves, then it will go to the
// next iteration...
await subscription.getAll(products[i]._id)
.then((subs) => {
// Make sure to return your promise here...
return update(subs, currentProduct);
});

// You could also avoid the .then by using two awaits:
/*
const subs = await subscription.getAll(products[i]._id);
await update(subs, currentProduct);
*/
}

或者,如果您只能使用简单的 promise ,则可以遍历所有产品,并将每个 promise 放入最后一个循环的 .then中。这样,它只有在前一个问题解决后才会前进到下一个问题(即使它将首先迭代整个循环):
let currentProduct;

let promiseChain = Promise.resolve();
for (let i = 0; i < products.length; i++) {
currentProduct = products[i];

// Note that there is a scoping issue here, since
// none of the .then code runs till the loop completes,
// you need to pass the current value of `currentProduct`
// into the chain manually, to avoid having its value
// changed before the .then code accesses it.

const makeNextPromise = (currentProduct) => () => {
// Make sure to return your promise here.
return subscription.getAll(products[i]._id)
.then((subs) => {
// Make sure to return your promise here.
return update(subs, currentProduct);
});
}

// Note that we pass the value of `currentProduct` into the
// function to avoid it changing as the loop iterates.
promiseChain = promiseChain.then(makeNextPromise(currentProduct))
}

在第二个代码段中,循环仅设置了整个链,但没有立即执行 .then中的代码。您的 getAll函数将不会运行,直到每个先前的函数依次解决为止(这是您想要的)。

关于javascript - 等待promise for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57281351/

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