Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

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.

like image 935
CleanTheRuck Avatar asked Jun 07 '13 17:06

CleanTheRuck


1 Answers

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) {
  ...
}
like image 111
robertklep Avatar answered Oct 30 '22 23:10

robertklep