0

When I run the code below, it always print 5, is there any way to save state? make it print 0, 1, 2, 3, 4?

for(var i=0; i<5; i++){
    fs.readFile("./test.txt", "utf8", function(err, data){
        console.log(i);
    });
}
  • 2
    possible duplicate of [Asynchronous Process inside a javascript for loop](http://stackoverflow.com/questions/11488014/asynchronous-process-inside-a-javascript-for-loop) – Ben Fortune Jun 09 '15 at 13:24

2 Answers2

1

You can create a closure (useful for this cases):

for(var i=0; i<5; i++){
    fs.readFile("./test.txt", "utf8", function(i) {
        return function(err, data) {
            console.log(i);
        };
    }(i));
}

You create an anonymous function, but with i in the scope. Note that you can get the numbers in a different order, as reading a file is an asynchronous operation:

> 0
1
2
3
4

or:

> 0
2
1
3
4
greuze
  • 4,250
  • 5
  • 43
  • 62
0

You could use promises for example.

var Q = require('q');
var fs = require('fs');

var readFile = function(i) {
  var deferred = Q.defer();

  fs.readFile("./test.txt", "utf8", function(err, data) {
    deferred.resolve(i);
  });

  return deferred.promise;
};

for (var i = 0; i < 5; i++) {
  readFile(i).then(function(result) {
    console.log(result);
  });
}
  • 1
    This works but I think there is a cleaner way to do it http://stackoverflow.com/questions/11488014/asynchronous-process-inside-a-javascript-for-loop – Michael Yuxi Dong Jun 09 '15 at 13:45