合并几个异步/等待调用的结果

编程入门 行业动态 更新时间:2024-10-08 00:33:58
本文介绍了合并几个异步/等待调用的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想通过调用许多 async/await 函数来返回合并结果.考虑下面我的(错误的)伪代码

I want to return the consolidated results from calling many async/await functions. Consider my (wrong) pseudocode below

const getRemoteData = async function(uri) { // get result from remote server via XMLHttpRequest return result; } const finalResult {}; const result1 = getRemoteData('…'); result1.forEach(async record => { // each record has a key for another URI const result2 = await getRemoteData(record["uri"]); // result2 has a key for yet another URI const result3 = await getRemoteData(result2["uri"]); finalResult[ result2["uri"] ] = result3; }) console.log(finalResult);

当然,由于 console.log(finalResult)在之前被调用,因此 forEach 循环中的所有临时调用均已完成,因此 finalResult 为空.在处理完 result1 中的所有条目之后,如何返回 finalResult ?我正在使用 nodejs 的最新版本,并且如果可能的话,宁愿不使用任何其他 Promise 库.据我了解,新的 async/await 功能应该使我能够完成自己想要的事情.

Of course, since console.log(finalResult) is called before all the interim calls in the forEachloop have completed, finalResult is empty. How do I return finalResult after all the entries in result1 have been processed? I am using the latest version of nodejs and, if possible, would rather not use any other Promise library. From what I understand, the new async/await capabilities should enable me to accomplish what I want.

推荐答案

您需要使用 .map 代替 .forEach 才能使用 .map result1 中的每个项目到一个 Promise 中,一旦关联的 result3 被分配给 finalResult ,该项目便会解析.然后,在该阵列上使用 Promise.all ,一旦其所有的承诺都解决了,它将解析,然后将在 finalResult 中填充您需要的所有内容:

You need to use .map instead of .forEach in order to .map each item in result1 to a Promise that resolves once the associated result3 has been assigned to finalResult. Then, use Promise.all on that array, which will resolve once all of its Promises have resolved, after which finalResult will be populated with everything you need:

const getRemoteData = function(uri) { // pretty sure you didn't mean to recursively call getRemoteData: return someApiCall(uri); } const result1 = await getRemoteData('…'); const finalResult = {}; await Promise.all(result1.map(async (record) => { const result2 = await getRemoteData(record.uri); const result3 = await getRemoteData(result2.uri); finalResult[result2.uri] = result3; })); console.log(finalResult);

(请注意,代替 await 的东西并立即返回它的 async 函数,您也可以 return <代替直接使用Promise -而且,点号通常比方括号更可取,方括号是当您需要使用变量属性名时使用的方式)

(note that instead of an async function that await's something and returns it immediately, you may as well just return the Promise directly instead - also, dot notation is usually preferable to bracket notation, bracket notation is when you need to use a variable property name)

更多推荐

合并几个异步/等待调用的结果

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

发布评论

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

>www.elefans.com

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