我有一个节点异步功能的例子。返回不是预期值的回调

时间:2014-07-06 02:56:47

标签: javascript node.js asynccallback

我编写了以下示例来测试node.js中的异步回调事件。事实是错误并没有给我一个参数。那是为什么?

var maxtime = 1000;

var evenDoubler = function(v, callback) {
    var waitTime = Math.floor(Math.random() * (maxtime + 1));
    if (v%2) {
        setTimeout(function() {
            callback(new Error("Odd input"));
        }, waitTime);
    }
    else {
        setTimeout(function() {
            callback(null, v*2, waitTime);
        }, waitTime);
    }
}

for (i=1;i<=10;i++) {
    evenDoubler(i, function (error, result, waitTime) {
    if (error){
        console.log(error + " by number " + i);
    }
    else {
        console.log("The number is even, and its double is " + result + " (in " + waitTime + " miliseconds).");    
    }
});   
}

返回的输出是(为什么在奇数上返回值11?)

Error: Odd input by number 11
Error: Odd input by number 11
The number is even, and its double is 20 (in 266 miliseconds).
The number is even, and its double is 12 (in 444 miliseconds).
Error: Odd input by number 11
The number is even, and its double is 4 (in 492 miliseconds).
The number is even, and its double is 16 (in 578 miliseconds).
The number is even, and its double is 8 (in 710 miliseconds).
Error: Odd input by number 11
Error: Odd input by number 11

1 个答案:

答案 0 :(得分:2)

这是因为您的for循环在第一次异步回调发生时已经完成,因此i在此时为11,这就是为if (error)记录的原因奇数所采用的路径。