问题
Given the following node.js module, how would I call the functions in the array orderedListOfFunctions
passing each one the response
variable?
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();
});
};
回答1:
You can use bind to do this like so:
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();
});
};
The bind
call prepends response
to the list of parameters provided to the one
and two
functions when called by async.series
.
Note that I also moved the results and next()
handling inside the callback as that's likely what you want.
回答2:
In keeping with OP's desire to do this without closing orderredListOfFunctions in the returned function:
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();
});
};
};
回答3:
Simple alternative is applyEachSeries -
applyEachSeries(tasks, args..., [callback])
Example -
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
});
来源:https://stackoverflow.com/questions/14305843/how-do-i-pass-a-standard-set-of-parameters-to-each-function-in-an-async-js-serie