Waiting for multiple HTTP requests JS
I am trying to make 3 requests to an API and then populate the array "pics" with the image URLs from each JSON response. Everything works fine but due to the asynchronous nature of JS when I return or print the array of URLs it is empty. How can wait until all 3 image URLs to have been added to the array before returning it? I am aware of js promises and async/await but I haven't had much luck getting those to work. Any help would be greatly appreciated.
function getPics(){
let json = "";
let pics = [];
for(i=0; i<3; i++){
var fetch = new FetchStream(someUrl);
fetch.on("data", function(chunk){
json = JSON.parse(chunk);
pics[i] = json.primaryImageSmall;
});
}
console.log(pics);
};
getPics();
Solution 1:
You can use Promises for that.
// Create each stream (in for loop or whatever)
const a = fetch('https://jsonplaceholder.typicode.com/todos/1');
const b = fetch('https://jsonplaceholder.typicode.com/todos/2');
const c = fetch('https://jsonplaceholder.typicode.com/todos/3');
// Then wait for all of them to resolve
Promise.all([a, b, c]).then((res) => console.log(res))
Check for doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all