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
asked Dec 15, 2017 at 6:20
Shukai Ni
4652 gold badges6 silver badges19 bronze badges
1 Answer 1
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
Sign up to request clarification or add additional context in comments.
Comments
lang-js
res => return res--- And no, it still is a promise. That function does nothing. You need to read some of those numerous blog posts about promises. -- "Still, this won't work." -- Of course it doesn't, you collect promises. Just read up on what promises are and how they work. Reading documentation (includes blog posts) goes a long way towards solving soooo many problems. This is not a question worth sharing and archiving on SO.