在for循环中使用async / await

编程入门 行业动态 更新时间:2024-10-28 04:19:20
本文介绍了在for循环中使用async / await的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何在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

本文发布于:2023-10-26 01:26:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1528677.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:async   await

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!