I have the following code in a Node.js application:
var curlStatus = "";
var curlBody = "";
var curlHeaders = "";
var curlInfo = curl.on('end', function( statusCode, body, headers){
curlStatus = statusCode;
curlBody = body;
curlHeaders = headers;
//this.close();
return {status: curlStatus, body: curlBody, headers: curlHeaders};
});
curl.on('error', function(){
console.log("CURL ERROR");
});
curl.perform();
Placing a breakpoint on return {status: curlStatus, body: curlBody, headers: curlHeaders};
shows that the body
, headers
, and statusCode
are being successfully populated. However, putting a breakpoint after curl.perform()
shows that the curlStatus
, curlBody
, and curlHeaders
variables are still empty strings. How do I pass the information to the parent function?
Welcome to javascript and asynchronous problem.
When you do curl.perform();
, the request will start but isn't yet done, that why your variable curlX
are not yet populated.
Once the request is done, the callback that you defined with url.on('end', function...
is called, and you will populate these variables.