0
const tileApiPromises = [];
 response.data.forEach((tile) => {
     return getPartnerToken(tile.id).then((response) => {
         tileApiPromises.push(getTileContent(tile, response));
     });
 });
 console.log(tileApiPromises) // should give me an array of promises
 Promise.all(tileApiPromises) // The goal is to execute this.

I am getting empty array of course in the log. How can I get array with promises outside the forEach. Thanks for your help!

1
  • When I tried with map, I get undefined promise value. :/ Commented Feb 24, 2017 at 10:12

2 Answers 2

1

The problem with your code is that the push is done asynchronously - therefore, there's nothing in the array yet!

you say you tried map (in the comment) - did you try it like this?

const tileApiPromises = response.data.map((tile) => {
     return getPartnerToken(tile.id).then((response) => {
         return getTileContent(tile, response);
     });
 });

or, sexier

const tileApiPromises = response.data.map(tile => 
    getPartnerToken(tile.id).then(response => getTileContent(tile, response))
);
Sign up to request clarification or add additional context in comments.

Comments

0

You can use Array.map function instead of forEach.

forEach always return undefined.

while map function iterates over array provided and returns accumulated array of values returned in callback provided in map function.

Here is nice documentation on map function. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map

2 Comments

I tried using .map, but when console.log(tileApiPromises), I get promiseValue undefined. Can you give me an example of how I can do this using map?
as @Jaromanda X mentioned in his answer. Did you try returning value in .then callback?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.