【问题标题】:await is only valid in async function within multiple for loopsawait 仅在多个 for 循环内的异步函数中有效
【发布时间】:2021-12-26 09:48:06
【问题描述】:
async function myfunc(fruits) {
for (i = 0; i < 5; i++) {
fruits.forEach(fruitId => {
colors = await dbHelper.getColor(fruitId);
colors.forEach(color => {
taste = await dbHelper.gettaste(color);
});
});
}
}
我们如何让它工作,有多个 for 循环。dbhelper 函数正在从数据库中获取一些数据。
【问题讨论】:
标签:
node.js
mongodb
for-loop
asynchronous
async-await
【解决方案1】:
您的代码有几个错误(请查看下方),应如下所示:
async function myfunc(fruits) {
try {
for (let i = 0; i < 5; i++) {
for (let fruitId of fruits) {
colors = await dbHelper.getColor(fruitId);
for (let color of colors) {
taste = await dbHelper.gettaste(color);
}
}
}
} catch(err) {
// Handle somehow
}
}
为什么?
- 您从
dbHelper 内部的 forEach 箭头函数而不是 myfunc 直接调用异步方法,因此此处不允许使用 await 关键字,您应该在调用异步方法的方法中添加 async 关键字。
- 在那里等待将不起作用,因为
forEach 循环无法暂停代码执行。解决方法:将forEach循环改成for (... in/of ...)。
- 您没有在任何地方处理错误。请记住,任何异步方法都可能被拒绝,因此您需要做好准备并以某种方式处理错误。解决方法:添加
try/catch。
您还可以查看this question 关于循环期间异步的信息。
【解决方案2】:
假设你想检索一个口味数组,你可以这样做
async function myfunc(fruits) {
const colors = await Promise.all(fruits.map(fruitId =>dbHelper.getColor(fruitId)));
const tastes = await Promise.all(colors.map(color => dbHelper.gettaste(color)));
...
}
或更短
async function myfunc(fruits) {
const colors = await Promise.all(fruits.map(dbHelper.getColor));
const tastes = await Promise.all(colors.map(dbHelper.gettaste));
...
}