在循环中使用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; }
它在控制台中引发这个错误:
等待是一个保留字
这个问题是关于这个我试图找出如何解决这个问题。
这取决于您希望如何执行asynchronous代码:按顺序还是并行执行。 无论如何,你需要添加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,而是希望它执行一些副作用的asynchronous操作。
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 }); }
但是这种方法实际上是一种反模式,因为它破坏了许诺链:对于可组合性,error handling等都是不利的。