Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js sending a response from a callback

I am using the express framework to handle requests. Some of the steps involve invoking asynchronous functions. Eventually I would like the return the value computed in one of these functions.

app.post("/hello", function(req, res) {
    ...
    ...

    myFunc(finalFantasy);
}

function myFunc(callback) {
    ...
    callback();
}

function finalFantasy() {
    //I want to return this value in the response
    var result = "magic";
}

How can I use the value calculated in finalFantasy function in the response?

like image 202
dopplesoldner Avatar asked May 23 '26 17:05

dopplesoldner


1 Answers

You have to pass the res instance to the callback, or use callback like the second example.

app.post("/hello", function(req, res) {
...
...

myFunc(finalFantasy, req, res);
}

function myFunc(callback, req, res) {
...
callback(req, res);
}

function finalFantasy(req, res) {
//I want to return this value in the response
var result = "magic";
res.end(result);
}

Another example is this:

app.post("/hello", function(req, res) {
    ...
    ...
    var i = 3;

    myFunc(i, function(data) {
        res.end(data); // send 4 to the browser
    });
}

function myFunc(data, callback) {
    data++; //increase data with 1, so 3 become 4 and call the callback with the new value
    callback(data); 
}
like image 133
Deepsy Avatar answered May 26 '26 07:05

Deepsy