8

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.

4

2 回答 2

16

您可以使用以下方法创建部分函数bind

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

该参数'image'将作为第一个参数传递给您的函数(其余参数将是 传递的参数async),所以它看起来像这样:

function urlToS3(fileType, url2fetch, cb) {
  ...
}
于 2013-06-07T18:21:17.467 回答
0

我刚刚在 iteratee 函数上使用 bind 方法解决了这个问题,以下是完整的工作示例:

var recordsToIterate = [
    {'id':"101", 'address':"Sample 1"},
    {'id':"102", 'address':"Sample 2"},
];

var person = {'name': "R", 'surname': "M"};

var funcProcessor = function(person, record, next){
    console.log(person); // object from recordsToIterate
    console.log(record); // person object
    next();
};

async.each(
    recordsToIterate,
    funcProcessor.bind(null, person),
    function(err){

    if(err){
        console.log(err);
    }
});

于 2019-12-04T11:01:06.177 回答