简体   繁体   中英

Pushing an Element into an Array Using Promises

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? 
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM