I’ve been wondering, is there a better way to pass variables into callback functions in node.js other than using bind().
Here is an example:
var fs = require('fs');
for(var i = 0; i < 100; i++) {
fs.writeFile(i + ".txt", i, function(error) {
fs.stat(this.i + ".txt", function() {
fs.rename(this.i + ".txt", this.i + ".new.txt", function() {
console.log("[" + this.i + "] Done...");
}.bind({ i: this.i }));
}.bind({ i: this.i }));
}.bind({ i: i }));
}
Notice the bind() methods all the way up, simply passing the value of i.
Thanks.
Variables in JavaScript are valid for the whole function scope.
This means that you can define a variable
x((var x = ...) and it is still accessible in all functions, you define within the same calling scope.(For detailed information you might want to take a look at JavaScript Closures
The problem of your case is, that you manipulate your
iduring thefor loop.If simply access the
iin the callback functions, you’d recieve the first value that is no longer in the loop.You can avoid that by calling a new function with the
ias argument, like this: