-2

The second part of a lambda function after first fetch request:

.then((articles) => {
  var images = [];
  for (let i = 0; i < articles.length; i++) {
    fetch(
      `example.com/${articles}`
    )
      .then((image) => image.json())
      .then((image) => {
        images.push([
          image["parse"]["title"],
          image["parse"]["images"][
            Math.floor(Math.random() * image["parse"]["images"].length)
          ],
        ]);
        console.log(images); \\ logs expected
      });
  }
  console.log(images); \\ logs empty array
  return images;
})

How can the .push() change the outer images variable?

Cyrus
  • 110
  • 6
  • 1
    it's showing an empty array because the fetch hasn't been done yet because it's asynchronous – sebasaenz Jan 31 '21 at 01:05
  • It does affect the outer scoped array. You're just doing a `console.log(images)` BEFORE the asynchronous operations in the loop have completed. – jfriend00 Jan 31 '21 at 01:10
  • 2
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – evolutionxbox Jan 31 '21 at 01:38

1 Answers1

1

It does affect the outer scoped array. You're just doing a console.log(images) BEFORE the asynchronous operations in the loop have completed.

Since you have a loop of asynchronous operations and they can all run in parallel, I would suggest using .map() to traverse the loop and build the output array of promises for you and then use Promise.all() to wait for all those promises to be done and collect all the results in order. You can do that like this:

.then((articles) => {
  return Promise.all(articles.map(article => {
      return fetch(`http://example.com/${article}`)
        .then(image => image.json())
        .then(image => {
            return [
            image.parse.title,
            image.parse.images[
              Math.floor(Math.random() * image["parse"]["images"].length)
          ];
        });
  })).then(allImages => {
      // this .then() handler is only here to we can log the final result
      console.log(allImages);
      return allImages;
  });
})
jfriend00
  • 683,504
  • 96
  • 985
  • 979