0

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();
3
  • make your function asynchronous, (prefix it with an async keyword), and await anything you need to wait for. i.e. async function fn() { await fetch(someUrl); await fetch(anotherUrl);} Commented Jan 11, 2022 at 21:04
  • I'd try with async/await, here's a great guide on this topic javascript.info/async-await Commented Jan 11, 2022 at 21:11
  • for loops are not asynchronous. Commented Jan 11, 2022 at 23:02

1 Answer 1

2

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

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

1 Comment

This would be the ideal solution for queue/task handling of many processes at once.

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.