为什么闭包没有通过异步获得正确的外部值? [英] Why the closures don't get correct outer values with async?

查看:49
本文介绍了为什么闭包没有通过异步获得正确的外部值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过 async 参见以下nodejs代码:

See the following nodejs code with async:

var async = require('async');

function inc(n, cb) {
    setTimeout(function() {
        cb(null, n+1);
    },1000);
};

var calls = [];

for(i=0;i<3;i++) {
    calls.push(function(cb){
        inc(i, cb);
    });
}

async.parallel(calls, function(err, results) {
    console.log(results);
});

它打印:

[4, 4, 4]

我不明白为什么结果不是 [1、2、3] ?

I don't understand why the result isn't [1, 2, 3]?

推荐答案

由于 calls 数组中的每个 call 都引用相同的 i 变量,认为这段代码:

Because every call in calls array references the same i variable, think this code:

function fn() {
    var i = 1;
    setTimeout(function() { alert(i); }, 500);
    i++;
    i++;
}
fn();

当然,这将输出 3 而不是 1 ,这与您的代码相同,变量 i 在更改之前呼叫执行;

This, certainly, would output 3 instead of 1, this is the same issue of your code, the variable i changed before the call executes;

为避免此问题,请用立即调用的函数表达式包装 for 循环,以创建一个新的作用域来存储 i

To avoid this problem, wrap for loop with a Immediately Invoked Function Expression to create a new scope to store the value of i

for (var i = 0; i < 3; i++) {
    (function(i) {
        calls.push(function(cb) { inc(i, cb); });
    }(i));
}

这篇关于为什么闭包没有通过异步获得正确的外部值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆