我可能不太明白为什么会发生这种情况,但我想帮助解决这个问题,以帮助我更好地理解使用http处理node.js请求并调用相同的函数。
这是模拟我想要在传入Web请求时使用的节点功能,但我希望它为每个调用使用单独的资源(如果这是正确的术语)。因此,对于每个请求,每个呼叫应该只触及它自己的数据..虽然它似乎没有发生,并且每个呼叫都踩在彼此的其他脚趾上。
setTimeout用于模拟可能需要一段时间的过程。
服务器代码:
var http = require("http");
var url = require("url");
var ts = require("test");
http.createServer(function(req, res){
pathName= url.parse(req.url).pathname;
var rc = "";
ts.process(function(rc) {
console.log(rc + " all done.");
});
res.writeHead(200, {"Content-type":"text/plan"});
res.end("thanks for the data!");
}).listen(5250, "192.168.201.40");
console.log("Listening on 192.168.201.40" + ":" + "5250");
"测试"来自require的代码:
var timeStamp;
function process(callback) {
timeStamp = Date.now();
console.log("test-in: " + timeStamp);
setTimeout(function() {
console.log("test-out: " + timeStamp);
callback(timeStamp);
}, 5000);
}
module.exports = {
process: process
}
客户请求代码:
var http = require('http');
var postData = "postdata";
var options = {
host: "192.168.201.40",
port: 5250,
path: '/',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData)
}
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function(chunk) {
console.log('Response: ' + chunk);
});
});
req.write(postData);
req.end();
当我调用测试样本代码一次来发出请求时,我得到了我期望的结果:
test-in: 1522107154345
test-out: 1522107154345
1522107154345 all done.
但是,如果我在完成其他函数调用之前调用测试函数3次,我会得到:
test-in: 1522107251094
test-in: 1522107251969
test-in: 1522107252939
test-out: 1522107252939
1522107252939 all done.
test-out: 1522107252939
1522107252939 all done.
test-out: 1522107252939
1522107252939 all done.
当我希望得到:
test-in: 1522107251094
test-in: 1522107251969
test-in: 1522107252939
test-out: 1522107251094
1522107251094 all done.
test-out: 1522107251969
1522107251969 all done.
test-out: 1522107252939
1522107252939 all done.
我确定我只是简单地通过javascript asyc编程来理解它。
答案 0 :(得分:1)
您的问题来自于变量timestamp
是在测试闭包之外定义的。拥有它你正在修改方法调用之间共享的全局状态或状态,在这种情况下结果是不可预测的。在函数process
中定义它,以便它的值包含在回调可访问的闭包中,您将修复该行为:
乐趣
ction process(callback) {
var timeStamp = Date.now();
console.log("test-in: " + timeStamp);
setTimeout(function() {
console.log("test-out: " + timeStamp);
callback(timeStamp);
}, 5000);
}