When you make an http request in node.js, it executes asynchronously. In node.js most functions that execute asynchronously take a callback
parameter as its last parameter. A callback is a function that executes when the request has finished. The parameters of that function usually take the form of (error, result)
.
So your callback function should first check for an error and then process the result. Because you need to use callbacks in node.js, you can't just return values directly like you would with a synchronous function. The result will always be a parameter in your callback function. Example:
var request = require('request');
function parseJson(callback) {
request('https://www.yourapi.com', function (error, response, body) {
if(error) {
callback(error, null);
} else {
var parsed = JSON.parse(body);
callback(null, parsed);
}
});
}
parseJson(function(error, parsedJson) {
if(error){
/* do something with the error */
} else {
console.log(parsedJson);
}
});
This is a very common pattern in node.js and is explained well in this answer. Using Promises is another solution.