简体   繁体   中英

Function in node.js always return undefined

I'm new at nodejs, and of course I see some guides/screencast to learn a little bit; but I'm very stoked about async/sync, read files and how nodejs handle the callbacks/returns. For example, I can't return the variable from this request query:

function call (method, parameters){
    fs.readFile("./cache/session", function(err, data){
        var pieces = data.toString().split(),
        sessionid = (method != "createsession") ? "/" + pieces[0] : "",
        vars = (!parameters) ? "/" + parameters : "",
        endpoint = "http://rest.svc/" + method + "json/";

        request({ url: endpoint}, function(error, response, body){
            if(!error) 
                return body;
        })
    })
}

'On the paper', I mean on javascript this will work perfectly, but in node always returns an undefined , I read other posts on stackoverflow about this, but no one clarifies me much as it should be.

Using you an Asynchronous functions, like call requires you to pass a callback parameter into the function, then the parameters of the callback is your "return" because the asynchronous function will return (undefined) before your fs.readFile responds.

function call (method, parameters, callback){
    fs.readFile("./cache/session", function(err, data){
     var pieces = data.toString().split(),
     sessionid = (method != "createsession") ? "/" + pieces[0] : "",
     vars = (!parameters) ? "/" + parameters : "",
        endpoint = "http://rest.svc/" + method + "json/";

        request({ url: endpoint}, function(error, response, body){
         if(!error) 
                callback(body)
        })
    })
}

In the function "call()", you start an asynchronous task. When that task has started, the function just continues. There is nothing else to do, so it returns undefined.

Now, when the asyncronous task calls it's callback, the callback doesn't really have anywhere to return the value, so it is discarded.

To get around this, you need to use something called Futures or Promises. I have never used these before myself, but they work something like this:

function call (method, parameters){
    var future = new Future();
    fs.readFile("./cache/session", function(err, data){
        var pieces = data.toString().split(),
        sessionid = (method != "createsession") ? "/" + pieces[0] : "",
        vars = (!parameters) ? "/" + parameters : "",
        endpoint = "http://rest.svc/" + method + "json/";

        request({ url: endpoint}, function(error, response, body){
            if(!error) 
                future.return(body);
            else
                future.throw(error);
        });
    });
    return future.wait();
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM