I am trying to call multiple external api within for loop but as per the result i am getting only one iteration from the for loop sending the response back.
Yes, its not the right approach to handle multi api request, please suggest the best approach as it has to be sequential req/res
First Request - Call to find respective api. Response holds the data to feed into two api which are called within for-loop.
For-loop Second API Request - feeds data to the third API request.
var express = require('express');
var bodyParser = require('body-parser');
var Request = require("request");
var app = express();
app.use(bodyParser.json());
app.post('/building/', function (req, res) {
'use strict';
var myObject = null;
var callSiteApi = {
uri: 'http://localhost:8080/site/',
body: JSON.stringify(req.body),
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
}
// First External API Call
Request(callSiteApi, function (error, response) {
if (error) {
console.log('ERROR with user request.');
return response.sendStatus(500); // Return back that an error occurred
} else {
// Get data from response.body
var materialquerystring = "mat="+response.body.material+"&date="+response.body.date;
var floor = response.body.floor;
for (var i = 0; i < floor.length; i++) {
matereialValueURL = "http://localhost:8080/material/q="+materialquerystring;
// Second External API Call within for loop
Request.get(materialValueURL, (error, response, body) => {
if (error) {
console.log(req.error);
}
materialObject = JSON.parse(body);
var valuequerystring = "value="+materialObject.value;
// do somehting with materialObject
console.log("first request iteration =" + i);
sitevalueURL = "http://localhost:8080/value/q="+valuequerystring;
// Third External API Call within for loop
Request.get(sitevalueURL, (error, response, body) => {
if (error) {
logger.debug('[' + pid + '] ' + req.error);
//return console.dir(error);
}
valueObject = JSON.parse(body);
console.log("second request iteration =" + i);
// do somehting with valueObject 7 materialObject
var a = materialObject.a;
var b = valueObject.b;
var c = a+b;
});
});
}
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end('{"value-1":"a","value-2":"b","value-3":"c","material":"materialquerystring","value":"valuequerystring"}');
}
});
});
Request's callback, callingreturnwill not work like you think it does, and theresponseis the one from the API call, notresfrom your/building/route handler. And making multiple requests like that isn't going to work with a simple for loop; you'll needPromise.all()for that.