Search code examples
javascriptnode.jscallbackasynccallbacknode-async

NodeJS: async module: passing arguments


I'm trying to pass arguments into a function in a NodeJS async queue with a callback. I can pass one argument correctly, but it fails for two.

Extract (abc is triggered by a HTTP POST request):

var queue = async.queue(doStuff, 5); 

var abc = function(request, response)
{
    queue.push(request, response, callback); 
}

var doStuff = function(request, response, callback)
{
    promiseChain...
    then(function(result) {
        //get stuff with result
        callback(response, stuff);
    }).close(); 
}

var callback = function(response, data)
{ response.writeHead(200, {'Content-Type':'text/plain'}); response.end(data); }

If I remove the response (or request) argument from the doStuff definition, then I can make it work. With two arguments + the callback, it throws any error saying the 2nd argument must be a callback function.

The doStuff function needs the request variable. The callback function needs to the response variable. Any idea how to implement? I tried put request and response into an array of objects but the array didn't pass into doStuff correctly.


Solution

  • If I remove the response (or request) argument from the doStuff definition, then I can make it work. With two arguments + the callback, it throws any error saying the 2nd argument must be a callback function.

    async.queue().push() only takes 2 arguments, push(task, [callback]). This is why you're only ever getting the first argument passed to your worker. Instead of flattening your parameters when passing them to queue.push() pass them in as an object

    queue.push({ req: request, res: response}, callback);
    

    Then in doStuff

    var doStuff = function(params, callback) {
        // Get our params from the object passed through
        var request = params.req;
        var response = params.res;
    
        promiseChain...
        then(function(result) {
            //get stuff with result
            callback(response, stuff);
        }).close(); 
    }