-->

我如何通过一套标准的参数,每个函数在async.js系列?(How do I pass a stan

2019-07-18 04:06发布

给定以下的node.js模块,我将如何调用的函数在阵列orderedListOfFunctions穿过每一个的response变量?

var async = require("async");
var one = require("./one.js");
var two = require("./two.js");

module.exports = function (options) {

var orderedListOfFunctions = [
    one,
    two
];

return function (request, response, next) {

    // This is where I'm a bit confused...
    async.series(orderedListOfFunctions, function (error, returns) {
        console.log(returns);
        next();
    });

};

Answer 1:

您可以使用bind来做到这一点,像这样:

module.exports = function (options) {
  return function (request, response, next) {
    var orderedListOfFunctions = [
      one.bind(this, response),
      two.bind(this, response)
    ];

    async.series(orderedListOfFunctions, function (error, resultsArray) {
      console.log(resultArray);
      next();
    });
};

所述bind呼叫预先考虑response于提供给所述参数列表onetwo当被调用的函数async.series

请注意,我也感动的结果和next()回调内部处理因为这是可能的,你想要什么。



Answer 2:

在与OP的愿望保持这样做没有在返回的功能关闭orderredListOfFunctions:

var async = require("async");
var one = require("./one.js");
var two = require("./two.js");

module.exports = function (options) {

  var orderedListOfFunctions = function (response) {return [
      one.bind(this, response),
      two.bind(this, response)
   ];};

   return function (request, response, next) {
      async.series(orderedListOfFunctions(response), function (error, returns) {
         console.log(returns);
         next();
      });
   };
};


Answer 3:

简单的方法是applyEachSeries -

applyEachSeries(tasks, args..., [callback])

例如 -

function one(arg1, arg2, callback) {
    // Do something
    return callback();
}

function two(arg1, arg2, callback) {
    // Do something
    return callback();
}

async.applyEachSeries([one, two], 'argument 1', 'argument 2', function finalCallback(err) {
    // This will run after one and two
});


文章来源: How do I pass a standard set of parameters to each function in an async.js series?