Map async functions over an array

2019-08-21 13:53发布

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)

Still, this won't work.

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?

Also I am using find-rss package over an array of links

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-08-21 14:05

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"] 
});

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

查看更多
登录 后发表回答