合并几个异步/等待调用的结果 [英] combining results from several async/await calls
问题描述
我想通过调用许多 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('http://…');
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 forEach
loop 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('http://…');
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)
这篇关于合并几个异步/等待调用的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!