gpt4 book ai didi

javascript - 我有一个 Node 异步函数示例。回调返回非预期值

转载 作者:行者123 更新时间:2023-11-30 17:24:06 25 4
gpt4 key购买 nike

<分区>

我编写了以下示例来测试 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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com