Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

240
Vistas
How to wait for multiple API calls to reutrn?

I have an array of APIs to query. For example var urls = ['example.org?x=1', 'example.org?x=2,3'] How can I have ReactJS wait for all the responses (which are JSON) to come back before responding to the client?

I've tried a modification @Shanoor's answer from Promises with http.get node.js but the result to the client is empty ("").

var http = require('http');
var urls = ['example.org', 'example2.org', '...'];

var done = 0;
var result = [];

function callback(index, data) {
  result[index] = data;
  done++;
  if (done == urls.length) {
    result.forEach(console.log);
    //I tried using the resp object here to return result[] but the data seemed corrupt 
  }
}

function processUrl(url, index) {
  var finalData = '';
  http.get(url, function(response) {
    response.setEncoding('utf8');
    response.on('data', function(data) {
      finalData += data;
    });
    response.on('error', console.error);
    response.on('end', function() {
      callback(index, finalData);
    })
  });
}

app.get("/api/blah", (resp) => {
  urls.forEach(processUrl);
  //resp(result); this would result in an empty response
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use Promise to do that, should be something like

function processUrl(url, index) {
  var finalData = '';

  return new Promise((resolve, reject) => {
    http.get(url, function(response) {
      response.setEncoding('utf8');
      response.on('data', function(data) {
        finalData += data;
      });
      response.on('error', reject);
      response.on('end', function() {
        resolve(finalData);
      })
    });
  })
}

app.get("/api/blah", (resp) => {
  Promise.all(urls.map(processUrl)).then(function(results) {
    console.log(results);
  });
}

Note that I didn't checked if the code is working, so please read more about Promises and the Promise.all() method

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda