How do you pass an argument to an iterator function for async.each?

I cannot for life find an answer to this question. How to pass an iterator function parameter for async.each using the caolan async.js node module? I want to reuse an iterator, but it needs to save things with a different context based prefix. I have:

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 would like 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 one similar question for coffeescript, but the answer did not work. I am open to refactoring in case I try to do something that is simply not idiomatic, but it seems like such a logical thing.

+6
source share
1 answer

You can create a partial function using bind :

 async.each(myArray, urlToS3.bind(null, 'image'), ...); 

The argument 'image' will be passed as the first argument to your function (the remaining arguments will be the arguments passed to async ), so it will look like this:

 function urlToS3(fileType, url2fetch, cb) { ... } 
+15
source

Source: https://habr.com/ru/post/946803/


All Articles