Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

241
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!