I have a function which consists of API PUT call. When I hit the function call update, The problem is the function gets returned first and then the request writes to API because of which I'm getting result as undefined. How can this be solved
//update function call
var result = update(object);
console.log('result ', result);
function update(obj){
var obj = obj;
var err = '';
var str = '';
var options = {
host: HOST,
port: PORT,
path: PATH + '/update/' + obj.id,
headers: { "content-type": "application/json" },
method: 'PUT'
};
try {
var request = http.request(options, function (response) {
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
util.log('\nsaved.' + str);
});
response.on('error', function (e) {
util.log('\nError while saving.' + e);
err = 'Something went wrong. Please try again later.';
});
});
var jsonObject = JSON.stringify(obj);
util.log('\n Sent to Update ' + jsonObject);
request.write(jsonObject);
request.on('error', function (e) {
util.log('\nError while updating request. ' + e);
err = 'Something went wrong. Please try again later.';
});
request.end('end', function(e){
util.log('On request end ' + str);
return (str || {err : err});
});
} catch (err) {
util.log("\nUpdating failed. " + err.stack);
return ({err: 'Failed to update. Please try again.'});
}
}