Reputation: 2853
I am currently stumped with a problem, where the http.request() just fails/skips to make a request to a given url. I have the following setup
async.waterfall([
firstFunc,
secondFunc,
thirdFunc
], function last(err, result){});
The thirdFunc is where i am making a request and it looks like the following
function thirdFunc(payload, callback){
var responseFromCS = getData(payload);
callback(null, responseFromCS);
}
The getData function looks like the following
function getData(obj){
var curlttogetdata = csConstants.BasePath + csConstants.account_num;
var accountNum = obj.customer.accountnum;
var resData = null;
curlttogetdata = curlttogetdata.replace('${accntNum}', accountNum);
var getData = {
hostname: csURLHost,
path: curlttogetdata,
method:'GET',
headers: {
'X-consumer-id': csConstants.ConsumerIDHeader,
'Content-Type':'application/json'
}
};
var req = http.request(getData, function (res){
var body = '';
res.on('data', function getData(chunk){
body += chunk
});
res.on('end', function parseData(){
try {
resData = JSON.parse(body);
}catch(err){
resData = false;
}
});
});
req.on('error', function csResponseError(err){
resData = false;
});
req.end();
return resData;
}
Now upon debugging, once the debugger reaches http.request(...) it fails to step into callback or make the request and then steps right into req.end(). There is no error returned back. I have looked at my parameters in the getData object a number of times and everything looks fine. Even tested this with a curl and gives back the expected response.
Upvotes: 0
Views: 59
Reputation: 2853
Ok so i believe i know the reasoning behind this. The 'http' node module is an async operation and the function getData that handles this, which is wrapped under thirdFunc in the async operation. I believe this operation gets executed before getData can respond.
So i moved the http.request() into thirdFunc and it works as expected.
Upvotes: 0
Reputation: 1159
one thing I see immediately is that you are returning resData as if it was a synchronous execution, meaning the httpRequest comes back after resData gets returned from your getData function, which will be null at that point
basically when your program is executing it does this 1 -makes http request, 2 -returns resData which is null (because the function executes until the end without stopping) 3 -the http request comes back and now resData has value but your function has already returned
what you need to do is pass a callback function instead of
var responseFromCS = getData(payload);
you do getData(payload, function(responseFromCS){
//..... do something with the returned data
});
Upvotes: 1