【问题标题】:Is it possible to pass additional arguments to async.eachSeries是否可以将其他参数传递给 async.eachSeries
【发布时间】:2012-12-26 05:30:18
【问题描述】:

是否可以向async.EachSeries传递额外的参数或参数

方法签名是:EachSeries(arr, iterator, callback)

我有一种方法可以将电子邮件收件人与邮件模板异步合并

var mergeTemplate = function(template,recipients,callback){

  async.EachSeries(recipients,processMails,callback);

};

var processMails = function(template,singleRecipient,callback){
   //...this would contain an async.waterfall of tasks to process the mail
   async.waterfall(tasks,callback);
}

我需要的是在不使用“脏”全局变量的情况下通过模板... 这可能吗?如果可以,怎么做?

谢谢

【问题讨论】:

  • 您可以使用一个对象将多个表达式封装在一个实体中。这是使用只接受一个用户定义参数的回调的常见解决方案。

标签: javascript node.js async.js


【解决方案1】:

您可以使用.bind 传递模板而不使用全局变量:

var mergeTemplate = function(template, recipients, callback){
    async.eachSeries(recipients, processMails.bind(processMails, template), callback);
};

bind() 方法创建一个新函数,在调用该函数时,将其 this 关键字设置为提供的值,并在调用新函数时提供的任何参数之前具有给定的参数序列。

所以processMails.bind(processMails, template) 创建了一个新函数,将this 设置为processMails,这个新函数的第一个参数是template

这相当于(但不那么冗长)直接像这样调用processMails

var mergeTemplate = function(template, recipients, callback){
    async.eachSeries(
      recipients, 
      function(){
         return processMails(template);
      }, 
      callback);
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多