0

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
  • 1
    What's the point of this function? To fill the space on screen? 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. Commented Dec 15, 2017 at 6:33

1 Answer 1

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.