node.js从callback中发送响应

我正在使用快速框架来处理请求。 其中一些步骤涉及调用asynchronous函数。 最终我想返回在这些函数之一计算的值。

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实例传递给callback函数,或者像第二个示例一样使用callback函数。

 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); } 

保持传递水平,并在你最后的“响应生成函数”中发送数据。 使用express的一般方法是使用中间件级联,在res.locals中存储持久值:

 app.get("/", function(req, res, next) { // do things next(); },function(req, res, next) { // do more things next(); },function(req, res, next) { // do even more things! next(); },function(req,res) { // and finally we form a response res.write(things); }); 

虽然你通常把它放在一个中间件文件中,然后包含它,调用它的函数:

 // middleware "lib/functions.js" file module.exports = { a: function(req, res, next) { ... }, b: function(req, res, next) { ... }, c: function(req, res, next) { ... } } 

然后在你的app.js,main.js或类似的明显的主文件中:

 var mylib = require("./lib/functions"); ... app.get("/", mylib.a, mylib.b, mylib.c); ... 

完成。 好的和有组织的,并通过next概念的stream自动传递。

//使用匿名函数包装finalFantasy

 app.post("/hello", function(req, res) { ... ... myFunc(function () { var ret = finalFantasy(); res.send(ret); }); } function myFunc(callback) { ... callback(); } function finalFantasy() { //I want to return this value in the response var result = "magic"; } 
 app.post("/hello", function(req, res) { ... ... var result = myFunc(finalFantasy); } function myFunc(callback) { ... return callback(); } function finalFantasy() { //I want to return this value in the response var result = "magic"; return result; } 

你几乎已经有了,就像@ raina77ow在评论中说的那样,把结果传回去