试图让我理解一个简单的nodejs处理i / o的异步方式和一个简单的下面的代码片段作为一个例子让我留下了问号。
// Just to simulate an io (webservice call).
var performRiskCheckViaWebservice = function(personPassportNumber, callback) {
console.log("Risk check called for personPassportNumber: "+personPassportNumber);
setTimeout(callback(personPassportNumber, "OK"), 5000);
}
function assessRisk(passportNumber) {
performRiskCheckViaWebservice(passportNumber, function(passportNumber, status){
console.log("Risk status of "+passportNumber+" is: "+status);
})
}
assessRisk("1");
assessRisk("2");
assessRisk("3");
在上面的简单代码片段中,我的期望是:
Risk check called for personPassportNumber: 1
Risk check called for personPassportNumber: 2
Risk check called for personPassportNumber: 3
And 5 seconds later:
Risk status of 1 is: OK
Risk status of 2 is: OK
Risk status of 3 is: OK
但实际输出是:
Risk check called for personPassportNumber: 1
Risk status of 1 is: OK
Risk check called for personPassportNumber: 2
Risk status of 2 is: OK
Risk check called for personPassportNumber: 3
Risk status of 3 is: OK
5秒钟后,程序停止。
我的理解有什么不对?
答案 0 :(得分:1)
事实证明,我必须在setTimeout(...)中使用匿名函数包装回调。这是工作版本:
// Just to simulate an io (webservice call).
var performRiskCheckViaWebservice = function(personPassportNumber, callback) {
console.log("Risk check called for personPassportNumber: "+personPassportNumber);
setTimeout(function() {
callback(personPassportNumber, "OK")
}, 5000);
}
function assessRisk(passportNumber) {
performRiskCheckViaWebservice(passportNumber, function(personPassportNumber, status){
console.log("Risk status of "+personPassportNumber+" is: "+status);
})
}
assessRisk("1");
assessRisk("2");
assessRisk("3");
答案 1 :(得分:0)
以下是代码的同步瀑布:
sync assessRisk
sync performRiskCheckViaWebservice
sync console.log Risk.check
sync callback <== problem here
sync console.log Risk status
sync setTimeout 5000
所以你观察到的是正常的。
你可以替换
setTimeout(callback(personPassportNumber, "OK"), 5000);
通过
setTimeout(callback.bind(null, personPassportNumber, "OK"), 5000);