简体   繁体   English

节点 js 中的关闭未按预期工作

[英]Closure in node js not working as expected

I have this piece of code:我有这段代码:

var responses = [];
for( var i=0; i < Number(process.argv[2]); i++) {
    responses.push(function () {
        var index = i;
        function bar() {
            console.log(index);
        }
        return bar;
    }());
}

responses.forEach(function(d){
    d();
});

where a closure is created by using an interim variable index .其中闭包是通过使用临时变量index创建的。 This outputs 0 1 as expected, printing the values I want to capture in a closure.这会按预期输出0 1 ,打印我想在闭包中捕获的值。

A similar code as http get callback doesn't work.与 http get 回调类似的代码不起作用。

var http = require("http");

var urls = ["http://yahoo.com","http://google.com"];

for( var i=0; i < urls.length; i++) {
   http.get( urls[i] , function(res) {
        var j = i;
        res.setEncoding('utf-8');
        res.on("data", function(d) {
            console.log(j);
        });
    });
}

This code outputs: 2 2此代码输出: 2 2

What am I missing?我错过了什么?

var j = i; will set the value of i which is length of the array on first response and that is the reason you get 2 every time you log it.将设置i的值, i第一次响应时数组的长度,这就是每次登录时都会得到2的原因。

Invoke a anonymous function as a second argument of http.get which will return inner function to handle response and it will also remember the environment in which it is created.调用一个匿名函数作为http.get的第二个参数,它将返回内部函数来处理响应,它还会记住创建它的环境。 Value of passed argument i will be there in the memory to be used later.传递的参数i值将在内存中供以后使用。

Try this:尝试这个:

 var http = require("http"); var urls = ["http://yahoo.com", "http://google.com"]; for (var i = 0; i < urls.length; i++) { http.get(urls[i], (function(i) { return function(res) { res.setEncoding('utf-8'); res.on("data", function(d) { console.log(i); }); } })(i)); }

There is no block scope in javascript(es5). javascript(es5) 中没有块作用域。 So the for loop that you used won't do the trick., Instead try:所以你使用的 for 循环不会成功。,而是尝试:

  urls.forEach(function(url, i){
      http.get( url , function(res) {           
        res.setEncoding('utf-8');
        res.on("data", function(d) {
            console.log(i);
        });
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM