如何在for循环中使用async / await?
How can I use async/await inside a for loop?
这是我的代码:
export default (req, callback) => { // ... compliance.forEach((rule, index) => { let response = await waRuleOverview(req, run.id, rule.id); // handle the response }); }这是我定义 waRuleOverview的方式 function:
This is how I define the waRuleOverview function:
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; }它在控制台中抛出此错误:
It throws this error in the console:
await是保留字
await is a reserved word
此问题与这个我试图弄清楚如何解决它。
This question is related to this one which I'm trying to figure out how to solve it.
推荐答案这取决于您希望如何执行异步代码:顺序执行或并行执行。无论如何,你需要添加 async 关键字来使用 await 。
It depends on how you want your async code to be executed: sequentially or in parallel. Anyway, you'd need to add async keyword to use 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但只是希望它为副作用执行一些异步操作。
And finally, if you don't really want your handler to return a Promise but just want it to perform some async actions for side effects.
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 }); }但这种做法实际上是一种反模式,因为它打破了承诺链:坏可组合性,错误处理等。
But this approach is actually an anti-pattern since it breaks promise chains: bad for composability, error handling and such.
更多推荐
在for循环中使用async / await
发布评论