Estoy tratando de hacer 3 solicitudes a una API y luego completar la matriz "fotos" con las URL de imagen de cada respuesta JSON. Todo funciona bien, pero debido a la naturaleza asíncrona de JS, cuando devuelvo o imprimo la matriz de URL, está vacío. ¿Cómo puede esperar hasta que se hayan agregado las 3 URL de imagen a la matriz antes de devolverla? Conozco las promesas js y async/await, pero no he tenido mucha suerte para que funcionen. Cualquier ayuda sería muy apreciada.
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();Puedes usar Promesas para eso.
// 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))Busque el documento: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all