Node.js 如何将一组标准参数传递给async.js系列中的每个函数?
给定下面的node.js模块,我将如何调用数组中的函数Node.js 如何将一组标准参数传递给async.js系列中的每个函数?,node.js,middleware,async.js,Node.js,Middleware,Async.js,给定下面的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 ];
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();
});
};
您可以使用这样做:
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();
});
};
当被async.series
调用时,bind
调用将response
前置到提供给one
和two
函数的参数列表
请注意,我还移动了回调中的结果和
next()
处理,因为这可能是您想要的。符合OP的愿望,即不关闭返回函数中的OrderRedListoff函数:
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
});
关于优化和重复的快速问题。。。如果不将orderedListOfFunctions关闭到函数中,没有理想的方法可以做到这一点?@Omega如果您希望它引用特定于调用的
响应
@johnyhk“this”在一个函数中指的是什么。“this”指的是什么。绑定(this,response)发生时?@Vishthis
将是导出函数调用的任何上下文。在使用bind
时,它实际上并不重要,因为该方法只是在函数调用的response
参数之前使用的。@JohnnyHK如果我也传递null,则此代码将起作用。在上面的例子中,上下文是什么?另外,如果我必须抽象async的最终匿名回调函数,并将响应绑定到它。这样行吗?在上述实现中,这是什么背景?