-1

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.'});
    }
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
jyoti
  • 101
  • 1
  • 9
  • Node.js is asynchronous in nature, you cannot expect a synchronous result from I/O like this. You need to use a callback, and for that you will need to read some tutorials. – John Zwinck Oct 14 '14 at 07:00
  • 2
    This is a dup of the hundreds of other questions by people who don't understand what an asynchronous response is. It is explained in great detail in http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call and http://stackoverflow.com/q/23667086/218196. The OP needs to read up on asynchronous result handling, starting with those two answers. The answer will be in either a callback or a more modern promise-based solution. Asynchronous code must be written differently due to the delayed timing of the response and the non-blocking nature of the call. – jfriend00 Oct 14 '14 at 07:05

1 Answers1

0

First you need to know about asynchronous and none-blocking.When your function is running, node is reading other codes and when the result is generated it return the value but now your other code that should show your answer on console is finished and printed it as undefined.

You can search about callbacks in node and many other things and first you should know your tools better :)

This is your code with true structure :

update(object ,function(result){
    console.log('result :', result);    
});

function update(obj,callback){
   ...
   // removed : return (str || {err : err});
   callback (str || {err : err});

   ...
   // removed : return ({err: 'Failed to update. Please try again.'});
   callback ({err: 'Failed to update. Please try again.'});
}
Elyas74
  • 548
  • 1
  • 5
  • 18