【问题标题】:How to pass context or attributes in async.js waterfall?如何在 async.js 瀑布中传递上下文或属性?
【发布时间】:2016-03-04 04:46:09
【问题描述】:

我想将当前上下文或属性传递给async.waterfall 中的函数。如何:

  1. 通过this
  2. 一个属性(这里是options对象)

这是我已经拥有的:

var _authenticate = function (cbAsync) {
  var licenseId = options.licenseId; //options is undefined
};
module.exports = new Command('createOrga')
  .description('creates an organization')
  .option('-f, --file <file>', 'the structure file including full path')
  .action(function (options) {
      options.confirm = options.confirm || true; // No confirmation needed!
      options.organizationUUID = (uuid.v4()).toUpperCase();
      options.licenseId = (uuid.v4()).toUpperCase();
      //How to pass options object to _authenticate function????
      async.waterfall([ _authenticate ], function(err) {
        if ( err ) {
          console.warn('Error in creating new organization: ',err);
        }
        else {
          console.info('Successfully created new organization: ' + organizationUUID);
        }
      });
    }
  }

【问题讨论】:

  • 你想通过哪个this
  • 上面贴的代码只是一个子集。问题是.action 中的上下文是否如this 可以传递给_authenticate

标签: javascript node.js node-modules async.js


【解决方案1】:

您可以使用Function.prototype.bind()传递变量。

async.waterfall([ _authenticate.bind(undefined, options)], function(err) {
    //your code
});

因为绑定的变量是首先传递的,所以你的回调必须如下所示:

var _authenticate = function (options, cbAsync) {
   var licenseId = options.licenseId; //options is undefined
};

【讨论】:

  • 所以undefined 作为第一个属性,this 可以提供上下文,对吧?
  • @DoK 是的。你传递的不是undefined,而是_authenticate 的新this,如果你传递this,那么它将与action 回调中的this 相同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-09
  • 1970-01-01
  • 2018-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多