I can't for the life of me find the answer to this. How do you pass a parameter to the iterator function for async.each using caolan's async.js node module? I want to reuse the iterator but it needs to save things with a different prefix based on the context. What I've got is:
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
}
What I'd like to be able to do is:
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
}
}
I found something one similar question for coffeescript but the answer didn't work. I'm open to refactoring in case i'm trying to do something that is just not idiomatic, but this seems like such a logical thing to do.
You can create a partial function using bind
:
async.each(myArray, urlToS3.bind(null, 'image'), ...);
The argument 'image'
would be passed as the first argument to your function (the rest of the arguments would be the arguments passed by async
), so it would look like this:
function urlToS3(fileType, url2fetch, cb) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With