在数组上映射异步函数 [英] Map async functions over an array
问题描述
我正在尝试在数组上映射一个异步函数,我希望达到这样的效果:
I am trying to map an async function over an array, I hope to achieve such effect:
const result = orgs.map(org =>
f(org)
.then(res => return res))
// now result should be an array of res
console.log(result)
这行不通,所以我尝试了另一种方法:
This would not work, so I tried another way:
const result = []
orgs.map(org =>
f(org)
.then(res => result.push(res)))
// now result should be an array of res
console.log(result)
仍然,这是行不通的.
但是我可以通过以下方式打印出结果:
But I can print out the result by doing:
orgs.map(org =>
f(org)
.then(res => console.log(res)))
关于这种行为如何发生的任何想法?
Any ideas on how this behavior happens?
我也在链接数组上使用 find-rss
包
Also I am using find-rss
package over an array of links
推荐答案
,您可以使用Promise.all()汇总多个Promise的结果.Promise是非常有用的JavaScript.
you can use Promise.all() to aggregate the results of multiple promises. Promise is very useful is javascript.
var p1 = Promise.resolve(3);
var p2 = 1337;
var p3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'foo');
});
Promise.all([p1, p2, p3]).then(values => {
console.log(values); // [3, 1337, "foo"]
});
这是一个简单的示例,众所周知,您的组织结构图结果是一个promise数组,因此您可以使用Promise.all来获取您想要的东西
this is a simple example, as u known, your orgs map result is an promise array, so you can use Promise.all to get what u want
这篇关于在数组上映射异步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!