简体   繁体   中英

Async.js Library Throws off Numbers in for loop

Using the Async Libeary for Node.js, trying to reference the variable in a for loop doesn't work.

For example:

var functionArray = []
, x;

for(x = 0; x < 5; x++) {
  functionArray.push(function (callback) {
    console.log(x);
    callback();
  });
}

async.series(functionArray, function (err, results) {
  console.log("Finished");
});

The output is:

5
5
5
5
5

It seems this is specific to the Async library. When you run the functions without the library, like so:

for(x = 0; x < 5; x++) {
  functionArray[x](function () {});
}

The output is:

0
1
2
3
4

I've noticed the same thing when using the async.parallel function.

Is there any way around this? What if you need to run a bunch of similar functions just with different numbers inside them (for instance, when indexing an array) and you need them to be run one right after the other rather than asynchronously? How can this be accomplished?

That's the same for any function that is called asynchronously, not just the async library. The function is called when the loop has completed, so the variable is at it's end state.

Wrap the code inside the function in an immediately executed anonymous function, so that you can create a separate variable for each iteration:

for(x = 0; x < 5; x++) {

  (function(y){

    functionArray.push(function (callback) {
      console.log(y);
      callback();
    });

  })(x);

}

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