node.js - 如何在递增循环之前等待异步进程在 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])
}
解决方案
看起来你快到了,只需将循环包装在一个函数中并使其异步即可。
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 以使其执行得更快
推荐阅读
- arduino - 连接arduino bord时,树莓派是否显示串口地址
- swiftui - UIHostingController 是否必须在视图控制器层次结构中?
- firebase - 请求的资源上不存在“Access-Control-Allow-Origin”标头。Firebase 托管
- mule - 在 mule4 中查找 multipart/form-data 文件的大小
- react-native - 通过 React Native 上的图标将焦点放在 InputTextMask 上时出错
- angular - Angular 11 排除未使用的类
- javascript - 如何使 2 个 ol 列表始终具有相同的顺序?
- javascript - 反应路由器尝试重定向用户的问题
- r - 如何从 dplyr 中的对象调用列名?
- python - 将字符串字典转换为字典 python