Node.js 异步瀑布上的属性值丢失
我试图模拟一个express响应对象,以便执行一些单元测试。到目前为止,我的模拟响应对象如下所示:Node.js 异步瀑布上的属性值丢失,node.js,express,node-async,Node.js,Express,Node Async,我试图模拟一个express响应对象,以便执行一些单元测试。到目前为止,我的模拟响应对象如下所示: module.exports.responseHelper = { response: "", send : function(val){ this.response = val; } } 我的问题是,如果我将此对象传递给如下方法: var async = require('async'); exports.sample = function (req,
module.exports.responseHelper = {
response: "",
send : function(val){
this.response = val;
}
}
我的问题是,如果我将此对象传递给如下方法:
var async = require('async');
exports.sample = function (req, res) {
async.waterfall([
function(callback){
callback(null, res);
},
function(res, callback){
callback(null, res);
},
function(res, callback){
callback(null, res);
}
], function (err, res) {
console.log("res before: " + res.response);
res.send("something4");
console.log("res after: " + res.response);
});
};
var route = require("../routes/testing");
var response = require("./requestHelper").responseHelper;
var req = {
params: {
someID: 1
}
}
route.sample(req, response);
console.log("final res: " + response.response);
这样称呼:
var async = require('async');
exports.sample = function (req, res) {
async.waterfall([
function(callback){
callback(null, res);
},
function(res, callback){
callback(null, res);
},
function(res, callback){
callback(null, res);
}
], function (err, res) {
console.log("res before: " + res.response);
res.send("something4");
console.log("res after: " + res.response);
});
};
var route = require("../routes/testing");
var response = require("./requestHelper").responseHelper;
var req = {
params: {
someID: 1
}
}
route.sample(req, response);
console.log("final res: " + response.response);
response.response值始终仅为“”(空字符串)
理想情况下,我不想更改路由实现,但我希望能够在瀑布结束时获得传递给发送的任何值。开始认为这是异步的,所以在请求响应之前,我可能需要一些额外的逻辑…我尝试了您的代码(复制/粘贴到您上面标识的3个单独文件中),这对我来说很好。我看到
res之前:
res之后:something4
。所以你上面所说的是正确的,不知道你是否有额外的处理会把事情搞砸。我编辑了代码…它在console.log(“final res:”+response.response)上;打印空值的地方…我猜这是因为async实际上是以异步方式运行的。是的,这是正确的。最终res
输出将在通过所有这些回调完成工作之前发生。如果您希望它在示例
完成后发生,您可以在那里包含回调(或承诺)——可能在res after
语句的某个地方调用它。