Because the request
method is asynchronous, you need to make your wrapper function asynchronous as well:
var post = function(data, callback) {
var r;
var options = {};
options.url = module.exports.apipath;
options.method = "POST";
options.form = data;
request(options, function(error, response, body) {
if (!error) {
if(response.statusCode == 200) {
try {
if((typeof body) == "string") {
var result = JSON.parse(body);
r = result;
} else {
r = body;
}
// Call callback with no error, and result of request
return callback(null, r);
} catch (e) {
// Call callback with error
return callback(e);
}
}
} else {
console.log("Error: " + error);
return callback(error);
}
});
}
Then you would call post
with a callback function as the second argument, to be run when the request was complete. By convention, your callback should take at least two arguments: an error
, which should be null
if everything works out okay, and a result
which is the result of the asynchronous process:
post ({foo: 'bar'}, function(err, result) {...});