鉴于以下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();
});
};
答案 0 :(得分: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
调用one
和two
函数前提供的参数列表前加上async.series
。
请注意,我还在回调中移动了结果和next()
处理,因为这可能是你想要的。
答案 1 :(得分:1)
符合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();
});
};
};
答案 2 :(得分: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
});