【问题标题】: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 函数正在从数据库中获取一些数据。

【问题讨论】:

  • 代替forEach,使用for..of循环,

标签: 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
    }
}

为什么?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-17
      • 1970-01-01
      • 2020-12-14
      • 2020-09-07
      • 2019-09-12
      • 1970-01-01
      • 2020-08-13
      • 2020-04-15
      相关资源
      最近更新 更多