Reputation: 91
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?
}
Upvotes: 1
Views: 103
Reputation: 1209
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.
Upvotes: 5