Search code examples
node.jsmiddlewareasync.js

How do I pass a standard set of parameters to each function in an async.js series?


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

};

Solution

  • 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.