waterfall with async

80 views
Skip to first unread message

Charlie Camus

unread,
May 15, 2014, 8:35:07 AM5/15/14
to nod...@googlegroups.com
Hi,

I'm trying to launch asynchronous method on serie way with async, But, you guess it, I can't did it.
Here is my code :

function findParam(userKey,callback){
    console.log("looking for params "+userKey);
    params.get(userKey,
        function(err, result, key) {
            var param = result;
            param.key=key;
            console.log("findParam "+param);
            callback(err, userKey, param);
        });
    console.log("done");
}

function findUsers(userKey,param, callback){
    console.log("looking fo uers "+userKey);
    console.log("Param "+param);
    users.get(userKey,
        function(err, result, key) {
            var user = result;
            user.key=key;
            console.log("user "+user);
            callback(err, user, param);
        });
}

launch code :

var user = findUserBySession(req.sessionID);
    async.waterfall(
        [
            findParam(user.key, callback),
            findUsers(arg1, arg2, callback)
        ]);

the stack trace :
looking for params 3edgl89
done
ReferenceError: arg1 is not defined... (lot of errors)
findParam [object Object]

That stack trace revealed to me that the second method is launched before the param was found. This is why the error appeared.
Can you help me ? What have I done wrong ?

Thank you !

Ben Trombley

unread,
May 16, 2014, 12:30:57 AM5/16/14
to nod...@googlegroups.com
The issue is that instead of passing findParam and findUsers as arguments to async.waterfall, you're calling them and passing the results (which is undefined).

You want:

async.waterfall(
        [
            async.apply(findParam, user.key),  // <-- this will pass user.key as the 1st argument to findParam, and async will pass the callback
            findUsers // <-- waterfall automatically passes the results from findParam's callback(err, user, param) to findUsers as parameters (except err)
        ], callback);

I hope that's helpful.
-Ben

Wil Moore

unread,
May 16, 2014, 12:59:56 AM5/16/14
to nod...@googlegroups.com
launch code :

var user = findUserBySession(req.sessionID);
    async.waterfall(
        [
            findParam(user.key, callback),
            findUsers(arg1, arg2, callback)
        ]);

You probably want:

async.waterfall([findParam.bind(null, user.key), findUsers]);


Reply all
Reply to author
Forward
0 new messages