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