如何将一组标准参数传递给async.js系列中的每个函数? [英] How do I pass a standard set of parameters to each function in an async.js series?

查看:340
本文介绍了如何将一组标准参数传递给async.js系列中的每个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下node.js模块,如何调用数组orderedListOfFunctions中的函数,并将每个变量传递给response变量?

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();
    });

};

推荐答案

您可以使用

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();
    });
};

bind调用在response之前将response附加到提供给onetwo函数的参数列表中.

The bind call prepends response to the list of parameters provided to the one and two functions when called by async.series.

请注意,我也将结果和next()处理移到了回调中,因为这很可能是您想要的.

Note that I also moved the results and next() handling inside the callback as that's likely what you want.

这篇关于如何将一组标准参数传递给async.js系列中的每个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆