简体   繁体   English

NodeJS数组的异常行为

[英]Unexpected behaviour of NodeJS array

I am currently learning how to use NodeJS and wrote this relatively simple function to run at a fixed interval. 我目前正在学习如何使用NodeJS,并编写了此相对简单的函数以固定间隔运行。 The aim of this function is to retrieve newly created Droplets and update their IP addresses. 此功能的目的是检索新创建的Droplet并更新其IP地址。

router.newDroplets = setInterval(function() {

    Server.find().then(function(svrs) {
        for (var i = 0; i < svrs.length; i++) {
            if (svrs[i].status == "Creating") {
                library.getDropletById(svrs[i].serverid).then(function(svr) {
                    if (svr.droplet) {
                        for (var j = 0; j < svr.droplet.networks.v4.length; j++) {
                            if(svr.droplet.networks.v4[j].type == 'public') {
                                var ip_address = svr.droplet.networks.v4[j].ip_address;
                                console.log(ip_address);

                                Server.update({serverid: svr.droplet.id}, {ipaddress: ip_address, status: "Online"}, function(error, n) {
                                    if (error) console.log(error);
                                    else console.log(n);
                                });
                            }
                        }
                    } else if (svr.id) {
                        // NOTE THIS LINE
                        console.log(svrs);
                    }

                }, function() {

                });
            }
        }
    }, function() {

    });

}, 2500);

The peculiar behaviour is with the line marked above. 特殊行为是上面标记的线。

When I use console.log(svrs) , I get an array of JSON documents in the Server collection in my MongoDB. 当我使用console.log(svrs) ,我在MongoDB的Server集合中获得了JSON文档数组。 However, when I use console.log(svrs[i]) , undefined is logged in the console. 但是,当我使用console.log(svrs[i])undefined会记录在控制台中。 This happens even if I declare var i = 0; 即使我声明var i = 0;也会发生这种情况var i = 0; outside the for loop. 在for循环之外。 Why is this happening and how can I access svrs[i] ? 为什么会发生这种情况,我如何访问svrs[i]

The way promises work is that the promise chains run asynchronously. 承诺工作的方式是承诺链异步运行。 By the time that code runs, i is equal to svrs.length , so svrs[i] will be undefined . 到代码运行时, i等于svrs.length ,因此svrs[i]将是undefined That's because the for loop executes in its entirety before any of the then callbacks are called. 这是因为for循环是在调用任何then回调之前完整执行的。 You could convert your code to use Array.prototype.forEach 您可以将代码转换为使用Array.prototype.forEach

So you can try something like 所以你可以尝试像

svrs.forEach(function(svrInstance, i) {
  if (svrInstance.status == "Creating") {
    library.getDropletById(svrInstance.serverid).then(function(svr) {
      if (svr.droplet) {
        ...
      } else if (svr.id) {
        console.log(svrs[i]);
      }
     });
   }
});

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

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