Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

74
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
}
7 months 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

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs