1

I am using map() over a long array and using fetch for each value. It will take many seconds to complete. I would like to know when the final push is complete and use the data in the array.

I tried Promise, Promise.all, Async/Await, but may have missed something obvious. I created this sample code to more simply illustrate the problem.

const arr = new Array(100).fill("todos")
const arrPush = []

const result = arr.map(data => {
  fetch(`https://jsonplaceholder.typicode.com/${data}`)
  .then(res => res.json())
  .then(res => arrPush.push(res))
})

Promise.all(result).then(() => console.log(arrPush))

When the final value is added to array, do something. In this case console.log the complete array.

1 Answer 1

3

The function that you're passing to map doesn't have a return statement, so result is an array of undefineds. As a result, there's nothing for Promise.all to wait for.

Additionally, there's no need to manually push into an array. Once we add in the return statement, you'll have an array of promises, and Promise.all will resolve to an array with all the stuff you're currently trying to push.

So try this:

const arr = new Array(100).fill("todos")
const promises = arr.map(data => {
  return fetch(`https://jsonplaceholder.typicode.com/${data}`)
    .then(res => res.json());
});

Promise.all(promises)
  .then(arrayOfResults => console.log(arrayOfResults));
Sign up to request clarification or add additional context in comments.

1 Comment

awsome thanks! I know thats where I started but headed down a wrong path. I think I assumed the return was the response, if that makes sense.

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.