给定以下的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();
});
};
您可以使用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()
回调内部处理因为这是可能的,你想要什么。
在与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();
});
};
};
简单的方法是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?