我正在使用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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句