asynchronous系列,如何使用具有特定绑定variables的函数
比方说,我有一个包含名称的表,我想在一个函数中使用所有的名字。 例如var names = ['joe','sam', 'nick'];
可以说我有以下function:
function doSomething (string1, NAME, string2, callback){ .... console.log(string1," ",NAME," ",string2); ... callback(null,"ok"); }
假设它是asynchronous的,我将使用async.each
函数。 此外,我想要传递函数中的variables,像这样使用绑定:
async.each(names,doSomething.bind(this, "example1", "example2",function(err){ console.log(err); });
我收到以下消息:
example1 example2 joe example1 example2 nick example1 example2 sam
我想要的是绑定在第一和第三个位置的string,并将名称分配给第二个。 可以这样做吗? 如何? 我在这里错过了JavaScript的基础知识吗?
我想要的是绑定在第一和第三个位置的string,并将名称分配给第二个。 可以这样做吗?
不与.bind
。 它只允许你绑定前n
参数,而不是前n
。
您可以简单地使用另一个function:
async.each(names, function(name, cb) { doSomething("example1", name, "example2", cb); });
并按照您喜欢的顺序传递参数。
这可能不是最漂亮的解决scheme,但可以包装doSomething函数并重新排列参数:
function doSomethingReordered(string1, string2, name, cb) { doSomething.bind(this)(string1, name, string2, cb); } async.each(names,doSomethingReordered.bind(this, "example1", "example2",function(err){ console.log(err); });