[英]NodeJS callback in a for-loop value is the same
我正在清理代码,在回调方面遇到了一些麻烦,特别是在调用回调时获取正确的值以进行输出。 有人可以向我解释为什么下面的代码在不需要将i的另一个参数放入run()函数的情况下吐出我所期望的东西以及可能的解决方案,或者在调用i时传入i以了解我的索引回调的唯一方法是这样做?
for (var i in dls) {
run(dls[i][0], dls[i][1], function(isTrue){
if (isTrue) {
// Do true stuff here
} else {
console.log("Value is: " + dls[i][3])
}
});
}
调用run()实际上内部具有正确的输入,但是在该函数调用回调并进入else语句时,dls [i] [3]会吐出相同的值i倍。
我试过在(run())周围放置不同的作用域,但无济于事,似乎无法解决这个问题。
谢谢
编辑:
如果我想将其拆分为一个单独的功能,该怎么办?
var run = function(cb){
setTimeout(function() {
cb(false)
}, 3000);
}
for (var i in dls) {
run(dls[i][0], dls[i][1], (function(index) {
return extraction
})(i));
}
function extraction(isTrue){
if (isTrue) {
// stuff
} else {
console.log("Nothing changed in " + dls[i][3])
}
}
此处dls [i] [3]仍然不正确,并打印相同的值3次。
您已经陷入了传统的“环路陷阱”
当您的回调运行的时间到了, i
现在是一个不同的值。
您可以做的是将该值缓存在另一个包装函数中:
for (var i in dls) {
run(dls[i][0], dls[i][1], (function (currentIndex) {
return function(isTrue){
if (isTrue) {
// Do true stuff here
} else {
console.log("Value is: " + dls[currentIndex][3])
}
};
})(i));
}
关于编辑/第二个问题,假设这是您想要做的:
// note that I changed the function signature of `run`
var run = function(val1, val2, cb) {
setTimeout(function() {
cb(false);
}, 3000);
};
// note the `wrapper` here
for (var i in dls) {
run(dls[i][0], dls[i][1], wrapper(i));
}
// this is the same as what the IIFE is doing,
// just with an external function instead
function wrapper(scopedIndex) {
// return a function to be used as the callback for `run`
return function extraction(isTrue) {
if (isTrue) {
// stuff
}
else {
// use the scoped index here
console.log("Nothing changed in " + dls[scopedIndex][3]);
}
}
}
function makeExitCallback(i)
看看另一个链接问题中的function makeExitCallback(i)
。 它直接关系到这里发生的事情。
您还应该发布dls
中的内容,以使在本地运行摘要更加容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.