首页 > 解决方案 > 如何在递增循环之前等待异步进程在 for 循环内完成

问题描述

我需要遍历一个数组。每次迭代,我都需要更新我的数据库。我需要等待第一次更新完成,然后进行第二次更新。在搜索了几个答案后,我发现了 ES2017 的 ASYNC/AWAIT 特性。但是,到目前为止,我还无法实现它。更新是随机发生的,而不是按顺序发生的。请让我知道如何在这种情况下实现 ASYNC/AWAIT 这是我的代码片段:

function findRecipe(product, qty) {
    return new Promise((resolve, reject) => {
        Recipe.findOne({
            product: product
        }, (err, recipe) => {
            if (err) {
                reject(err)
            } else {
                for (let i = 0; i < recipe.items.length; i++) {

                    Item.findOne({
                        name: recipe.items[i].name
                    }, (err, item) => {
                        if (err) {
                            reject(err)
                        } else {
                            var lessAmt = recipe.quantities[i] * qty;
                            item.stock -= lessAmt;
                            item.save((err, item) => {
                                if (err) {
                                    console.log(err)
                                } else {
                                    resolve(item)
                                }
                            })
                        }
                    })
                }
            }
        })
    });
}

for (let i = 0; i < bill.product.length; i++) {
    //Calling function for updates for each item
    findRecipe(bill.product[i], bill.qty[i])
}

标签: node.jsmongodbasync-await

解决方案


看起来你快到了,只需将循环包装在一个函数中并使其异步即可。

async function updateAllRecipe(){
 for(let i=0;i<bill.product.length;i++){
 //Calling function for updates for each item
 await findRecipe(bill.product[i],bill.qty[i])
 }
}

但说真的,我认为您可以在这里使用 Promise.All 来利用并行性。在排队下一个 findRecipe 方法之前真的有必要等待配方完成吗?如果不使用 promise.all 以使其执行得更快


推荐阅读