简体   繁体   中英

Node.js: how to loop through handling incoming data?

I have received this comment:

On the server side of Node.js when handling incoming data if you want to use a for loop you have to create i inside an anonymous function or you will pull your hair out wondering how the hell your variable i is greater than what you limit it to be inside your loop.

Here is the bugfix that was recommended:

var i = 0,
len = that.users.length;

(function(i) {
  while(i < len) {
    console.log(' - - - - - debug - - - - -');
    console.log('i = ' + i );
    i++;
  }
})(i);

Can someone explain to me why using an anonymous function is necessary?

The problem only shows up when you have asynchronous code inside the loop. For example (I changed to a for loop for simplicity):

var i = 0,
len = that.users.length;

for(i = 0;i < len;i++) {
  setTimeout(function() {
    console.log('i = ' + i );
  }, 500);
}

You will find that running this code causes the value of len to be printed len times, instead of a count up to len . This is because the for loop finishes before any of the print statements run, so the loop has exited because i == len .

The fix for this is to lock i in to each value with an Immediately-Invoked Function Expression (IIFE):

var i = 0,
len = that.users.length;

for(i = 0;i < len;i++) {
  (function(i) {
    setTimeout(function() {
      console.log('i = ' + i );
    }, 500);
  })(i);
}

This isn't exactly the bugfix you presented, but it is the closest I can think of that makes much sense. Given more context, I could be more sure about what problem it is supposed to solve.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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