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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With