Im a bit confused on how the this code is getting compiled. What Im essentially trying to do is fetch urls from an array and storing the responses in a result array.
However my confusion arises when I try to log the output of my result array. The console log call gets executed before the function calls even if I use await or even if I use Promise.all
The console shows output of console.log after function call first and then the result array gets updated I know this because I used a setTimeout to confirm if I setTimeout for the console.log after function call for 5 seconds the correct order is displayed
Here are both implementations:
With Promise.all
let result = [];
let fetchURLS = urls => {
return Promise.all(
urls.map(item => {
fetch(item)
.then((response) => {
if (response.ok) {
return response.json();
}
})
.then(data => {
console.log("data: ", data);
result.push(data);
})
.catch((error) => {
console.log('Invalid URL');
result.push('Invalid URL');
});
})
);
}
let urls = [
"https://fakestoreapi.com/products/categories",
"https://fakestoreapi.com/products/1"
];
let main = () => {
fetchURLS(urls).then( () => {
console.log("-----------------");
console.log("Result Array -> ");
console.log(result);
});
}
main();
With await
let fetchURLS = urls => {
urls.map(item => { ....
...}
let main = async () => {
await fetchURLS(urls);
console.log("-----------------");
console.log("Result Array -> ");
console.log(result);
}
OUTPUT :
"-----------------"
"Result Array -> "
// [object Array] (0)
[]
"data: " // [object Array] (4)
[1,2,3,4]?
"data: " // [object Object]
{"id" : 1}