3

给定以下 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();
    });

};
4

3 回答 3

3

您可以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()回调中移动了结果和处理,因为这可能是您想要的。

于 2013-01-13T17:18:13.913 回答
1

在不关闭返回函数中的 orderredListOfFunctions 的情况下,符合 OP 的愿望:

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();
      });
   };
};
于 2014-05-04T15:01:37.730 回答
0

简单的替代方法是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
});
于 2016-02-10T07:46:37.097 回答