javascript - 在 for 循环中使用 async/await

标签 javascript node.js async-await

<分区>

如何在 for 循环中使用 async/await?

这是我的代码:

export default (req, callback) => {
  // ...
  compliance.forEach((rule, index) => {
    let response = await waRuleOverview(req, run.id, rule.id);
    // handle the response
  });
}

这就是我定义 waRuleOverview 函数的方式:

export function waRuleOverview(req, runId, ruleId) {
  var def = deferred();

  setTimeout(function() {
    const apiToken = req.currentUser.apiToken;
    const payload = {
      'Authorization': 'api_key ' + apiToken
    }

    const options = {
      'method': 'get',
      'gzip': true,
      'headers': payload,
      'content-type': 'application/json',
      'json': true,
      'url': 'api-url'
    }

    request(options, (error, response, body) => {
      def.resolve(body);
    });
  }, 50);

  return def.promise;
}

它在控制台中抛出这个错误:

await is a reserved word

这个问题与this有关一个我想弄清楚如何解决它。

最佳答案

这取决于您希望如何执行异步代码:顺序执行还是并行执行。无论如何,您需要添加 async 关键字才能使用 await

// sequential
export default async (req, callback) => {
  // ...
  for(const [rule, index] of compliance.entries()) {
    const response = await waRuleOverview(req, run.id, rule.id)

    // handle the response
  }
}

// parallel
export default async (req, callback) => {
  // ...
  const responses = await Promise.all(compliance
     .map((rule, index) => waRuleOverview(req, run.id, rule.id))
  )

  // handle responses
  responses.forEach(response => {
    // ...
    // handle response here
  })
}

最后,如果您真的不希望处理程序返回 Promise,而只是希望它执行一些异步操作以产生副作用。

export default (req, callback) => {
  // ...
  compliance.forEach(/* add */ async (rule, index) => {
    // to use await inside
    let response = await waRuleOverview(req, run.id, rule.id);
    // handle the response
  });
}

但这种方法实际上是一种反模式,因为它打破了 promise 链:不利于可组合性、错误处理等。

关于javascript - 在 for 循环中使用 async/await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45505517/

相关文章:

javascript - Google 脚本编辑触发器

javascript - 如何在nodejs中删除请求头中的单引号

sql - 像这样的内连接如何转换为Sequelize?

C# backgroundworker RunworkerCompleted 与异步等待

swift - 如何通过新尝试获取下载进度 await URLSession.shared.download(...)

javascript - 将字符串 Date 转换为 new Date() 并以相同格式再次转换回来

c# - 文字换行以适合一定比例(不是大小)的矩形

javascript - Box Node SDK 未使用 readStream 拉取文件

javascript - Modal Div 不是从 javascript 调用

node.js - 尝试代理到 : localhost:3000/api on a M1 Macbook 时出错