1

When I console.log my array it remains empty, so I am failing to push the element into the array with my code. I can do it outside of a function, but do not know what I am doing wrong here with the promises. I am new to promises. Thanks for any tips:

function fetchApiData(num) {
 let arr = []; 

for(let i = 0; i < num; i++) {
  fetch('https://dog.ceo/api/breeds/image/random')
  .then(response => response.json())
  .then(responseJson => console.log(responseJson.message))
  .then(responseJson => arr.push(responseJson.message));
  console.log(arr);
  }
  console.log(arr);  
  // how do I change console.log to push value into an array? 
}
1
  • What's your issue exactly? The items aren't going to be pushed into the array until those fetches have all be resolved. You'd have to wait for them to finish before examining the array Commented Oct 25, 2018 at 19:00

1 Answer 1

5

Your issue is the order of resolution. Namely, when your code executes, here is what happens:

0.) Arr = []

1.) Start for loop

2.) Initiate promise

3.) log arr

4.) loop finishes

5.) log arr

6.) At some undefined point in the future, a few milliseconds later, your promises resolve, one at the time, each adding the element to the array.

Try capturing the promises in an array and using

Promise.all(promiseArr).then(()=>{
    console.log(arr)
})

Promise.all will wait till all the promises in the array have finished before executing, so you'll be able to log your completed array.

Sign up to request clarification or add additional context in comments.

Comments

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.