将variables传递到Node.js中的callback函数的最佳方法

我一直在想,除了使用bind()之外,还有更好的方法将variables传递到node.js中的callback函数中。

这里是一个例子:

 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 })); } 

注意bind()方法,直接传递i的值。

谢谢。

JavaScript中的variables对于整个函数范围是有效的。 这意味着你可以定义一个variablesx (( var x = ... ),并且它仍然可以在所有的函数中访问,你可以在同一个调用范围内进行定义(有关详细信息,您可能需要查看JavaScript闭包

你的情况的问题是,你在for loop操纵你。 如果只是在callback函数中访问i ,则会收到不在循环中的第一个值。

你可以通过调用一个新的函数作为参数来避免这种情况,例如:

 var fs = require('fs'); // still use your for-loop for the initial index // but rename i to index to avoid confusion for (var index = 0; index < 100; index++) { // now build a function for the scoping (function(i) { // inside this function the i will not be modified // as it is passed as an argument fs.writeFile(i + ".txt", i, function(error) { fs.stat(i + ".txt", function() { fs.rename(i + ".txt", i + ".new.txt", function() { console.log("[" + i + "] Done..."); }); }); }); })(index) // call it with index, that will be i inside the function } 

我想在下面做:

 var fs = require('fs'); var getWriteFileCallback = function(index) { return function(error) { fs.stat(index + '.txt', function() { fs.rename(index + '.txt', index + '.new.txt', function() { console.log("[" + index + "] Done..."); }); }); }; } for(var i = 0; i < 100; i++) { fs.writeFile(i + ".txt", i, getWriteFileCallback(i)); } 

你可以在for循环中使用let而不是var。 这是(至less在我看来)两者之间的最大区别! 只要确保你使用严格的模式,或让我们不会为你工作。

 var fs = require('fs'); for(let i = 0; i < 100; i++) { fs.writeFile(i + ".txt", i, function(error) { fs.stat(i + ".txt", function() { fs.rename(i + ".txt", i + ".new.txt", function() { console.log("[" + i + "] Done..."); }); }); }); }