我正在使用 express 框架来处理请求。一些步骤涉及调用异步函数。最后,我希望返回在这些函数之一中计算的值。
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";
}
如何在响应中使用在 finalFantasy 函数中计算的值?
最佳答案
您必须将 res
实例传递给回调,或者像第二个示例那样使用回调。
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);
}
另一个例子是这样的:
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);
}
关于javascript - node.js 从回调发送响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20664745/