如何将parameter passing给async.each的迭代器函数?
我不能为了我的生活find答案。 如何使用caolan的async.js节点模块将parameter passing给async.each的迭代器函数? 我想重用迭代器,但它需要根据上下文使用不同的前缀来保存内容。 我得到的是:
async.each(myArray, urlToS3, function(err){ if(err) { console.log('async each failed for myArray'); } else { nextFunction(err, function(){ console.log('successfully saved myArray'); res.send(200); }); } }); function urlToS3(url2fetch, cb){ //get the file and save it to s3 }
我想要做的是:
async.each(myArray, urlToS3("image"), function(err){ if(err) { console.log('async each failed for myArray'); } else { nextFunction(err, function(){ console.log('successfully saved myArray'); res.send(200); }); } }); function urlToS3(url2fetch, fileType, cb){ if (fileType === "image") { //get the file and save it to s3 with _image prefix } }
我发现了一些类似于咖啡的问题,但答案并不奏效。 我打算重构,以防万一我试图做一些只是不习惯的东西,但这似乎是这样一个合乎逻辑的事情要做。
您可以使用bind
创build一个部分函数:
async.each(myArray, urlToS3.bind(null, 'image'), ...);
参数'image'
将作为函数的第一个parameter passing(其余参数将是async
传递的参数),所以它看起来像这样:
function urlToS3(fileType, url2fetch, cb) { ... }