在for循环中使用async/await

3

如何在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 是一个保留字

这个问题与这个问题相关,我正在努力解决它。


我尝试过了,但仍然出现那个错误。 - Valip
@Andreas 为什么?OP 在 waRuleOverview 中没有使用 await,但是返回了一个 Promise。 - Yury Tarabanko
1个回答

15

这取决于您希望异步代码是按顺序执行还是并行执行。无论如何,您都需要添加 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 链:这对于可组合性、错误处理等方面都是不利的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接