如何使用基于索引的参数创build一个函数数组

我有一组函数,它们通过async.series()函数运行,这些函数将参数作为参数存储在一个数组中。

 params = [ {id: 1, name: "Two tires fly. Two wail."}, {id: 2, name: "Snow-Balls have flown their Arcs"}, {id: 3, name: "A beginning is the time for taking the most delicate care"} ]; async.series( [ function(callback) { myFunction(callback, params[0]); }, function(callback) { myFunction(callback, params[1]); }, function(callback) { myFunction(callback, params[2]); }, ]); 

显然,数组要大得多,将它们包装成一个循环会很方便:

 var functionsArray = []; for (var i = 0; i < params.length; ++i) { functionsArray.push( function(callback) { myFunction(callback, params[i]); } ); } async.series(functionsArray); 

唉,这种技术使得jshint在数组中定义一个函数时会感到怪异,我明白为什么它不起作用。 在通话时i将是一个固定的价值,并不被视为价值。

如何创build一组参数在数组中的函数,以便我不必显式定义每个函数。

我愿意在async使用其他设施。 而且,这些函数是非常asynchronous的,因此使用async.series()

你可能想要async.eachasync.eachSeries (第一个并行工作):

 async.eachSeries(params, function(param, callback) { myFunction(callback, param); }, function(err) { // Put code that needs to run when its all finished here }) 

但是,这可能会更容易。 如果myFunction使用最后一个callback参数(这是node.js中的常态),则可以删除额外的匿名函数:

 async.eachSeries(params, myFunction, function(err) { // Put code that needs to run when its all finished here }) 

如果你用callback最后的签名来编写你的函数,那么他们将更有可能和node.js库很好的一起玩。

唉,这种技术使得jshint在数组中定义一个函数时会感到怪异,我明白为什么它不起作用。

我假设你的意思是“在循环中定义一个函数”? 如果是这样,这是因为定义函数相当昂贵,jshint阻止 – 不是因为它不会工作。 它也可能已经认识到, i不会是你想要的 – 这将是最终的价值,因为如何closuresJavaScript的工作。 一般来说,你应该避免在一个循环中定义函数,但是你可以用一个IIFE(立即调用的函数expression式)来避免i问题:

 for (var i = 0; i < params.length; ++i) { (function(i) { functionsArray.push( function(callback) { myFunction(callback, params[i]); } ); })(i); } 

你可以通过把你想要的东西包装在一个本地化的“我”。 自我调用function:

 params = [ {id: 1, name: "Two tires fly. Two wail."}, {id: 2, name: "Snow-Balls have flown their Arcs"}, {id: 3, name: "A beginning is the time for taking the most delicate care"} ]; var currentlyFinished = 0; function finished () { currentlyFinished ++; if( currentlyFinished == params.length ) { // // you will end up here after all the params have been run thru your function // If you need a list sorted after all the callbacks, you'd do that here // } } for (var i = 0; i < params.length; ++i) { (function(currentIndex) { // 'i' becomes 'currentIndex', which is local to the anon. function myFunction( params[currentIndex], function () { finished (); }); })(i); // here is where you 'call' the anon. function, passing 'i' to it } 

作为一个说明,我从来没有使用asynchronous库,但它确定。 看起来像是一个有用的工具,有很多其他的方法可以用更简单的方法来实现; 我喜欢先解决问题,理解它们,一旦我明白了,这些库就可以完成重任。