Hej,
I’m experimenting with node.js and its callback mechanism. And now I wonder how to overhand data to such an anonymous callback:
var fs = require('fs');
for (var i = 0; i < 4; i++) {
console.log('Outer: ' + i);
fs.readFile('/etc/hosts', 'ascii', function(err, data) {
console.log('Inner: ' + i);
});
}
I do understand why the inner call to i returns 4 always. But how can I supply some variables to that specific readFile-callback function (so that the inner i will have the value of the outer i)? I could imagine some queue mechanism, where the callback function acts as a consumer, but as a node beginner I’d like to ask for the best practices. Thanks a lot,
mechko
With the pure Javascript (that is, not using libraries such as async):
Or, alternatively,
(moving the
var i;declaration out of theforloop does not really changes anything in this specific example, it is just a code style to prevent the bugs related to Javascript, as opposed to the programming languages like Java, having only the function scope for variables – so that, in your original example,iis declared for the entire module, not just forforloop).Alternative approach would be to use libraries such as
asyncandunderscorelike this: