Freya Freya - 1 month ago 10
Javascript Question

Async - callback is not a function

I am trying to work with async in node js, to control the flow of execution of some functions. In the code below I have three declared functions that should print respectively 'one', 'two' and 'three', along with performing other tasks (the printing is only so that I can see what gets executed when).

async.waterfall([
function(callback) {
settings();
console.log("1");
callback(null, 'one');
},
function(callback) {
profile();
console.log("2");
callback(null, 'two');
},
function(callback) {
console.log("3");
groups();
callback(null, 'two');
}
]);


So I get the error "callback is not a function" in the line of callback(null, 'two');
To be honest, this might as well be a very dummy question, and I do not fully understand how async waterfall works. But I seriously did try, by reading examples, trying to implement short code and trying to play around with it.

Interesting that if async.series is used instead of async.waterfall, there is no such error. However async.series will print 1, 2, 3, three, one, two.
The numbers inside the waterfall model are printed in sequence, but the functions inside are not executed in the right order.

It is to be noted that the first two functions - settings and profile - include db reading and calculations whereas the third only prints some results.

Answer

With async.waterfall, results are passed to the next function as arguments. For example:

async.waterfall([
    function(callback) {
        callback(null, 'one', 'two');
    },
    function(arg1, arg2, callback) {
        // arg1 now equals 'one' and arg2 now equals 'two'
        callback(null, 'three');
    },
    function(arg1, callback) {
        // arg1 now equals 'three'
        callback(null, 'done');
    }
], function (err, result) {
    // result now equals 'done'
});

In your case, callback on the second function will have received the string one as argument. And thus the error you are experiencing.

Comments