如何将参数传递给async.each的迭代函数?

8

我总是找不到这个问题的答案。如何使用Caolan的async.js节点模块将参数传递给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
    }
}

我找到了一个类似的关于coffeescript的问题,但是答案不起作用。如果我正在尝试做一些不符合惯用法的事情,我可以进行重构,但这似乎是一件非常合乎逻辑的事情。

2个回答

16

您可以使用 bind 创建一个部分函数:

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

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

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

function urlToS3(fileType, url2fetch, cb) {
  ...
}

谢谢,非常完美。代码好看、DRY。按照 @nirk 的建议返回不同的函数将导致我希望避免的代码重复。谢谢! - CleanTheRuck
@Startec 请查看此文档 - robertklep

0

我刚刚使用迭代函数的绑定方法解决了它,以下是完整的工作示例:

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);
    }
});


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接