await仅在多个for循环中的异步函数中有效


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函数正在从数据库中获取一些数据。

您的代码有几个错误(请查看下面的内容(,应该如下所示:

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
}
}

为什么

  1. 您从forEach箭头函数内部的dbHelper调用异步方法,而不是直接从myfunc调用,因此不允许使用await关键字,您应该将async关键字添加到异步方法调用的方法中
  2. 由于forEach循环无法暂停代码执行,因此等待在那里将不起作用。解决方案:将forEach循环更改为for (... in/of ...)
  3. 你没有在任何地方处理错误。请记住,任何异步方法都可能被拒绝,因此您需要做好准备并以某种方式处理错误。解决方案:添加try/catch

您还可以检查这个关于循环期间异步的问题。

假设你想检索一个口味数组,你可以做这样的

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));
...
}

最新更新