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