willconant / flow-js

Javascript Library for Multi-step Asynchronous Logic
MIT License
302 stars 15 forks source link

Maintaining access to scope vars in flow.exec #16

Closed tiagosiebler closed 6 years ago

tiagosiebler commented 7 years ago

I'm trying to avoid async callback hell by creating a flow for a more complex set of API calls. Currently I have something like this: //var lookupSQL can't go here

    flow.exec(
        function(){
            // see if user is in lookup table
            var lookupSQL = "SELECT * FROM ?? WHERE slackUserID = ?";
            pool.query(lookupSQL, [usersLUTable, message.user], this.MULTI("lookup_user"));

            // need to pass these on, or they won't be visible in the next function() call
            this.MULTI("params")(bot, message, callback, pool, this);
        },function(results){
            var bot = results.params[0],
                message = results.params[1],
                callback = results.params[2];

            if(results.lookup_user[0]){
                // error in SQL query
            }

            var results = results.lookup_user[1];
            var isKnownUser = false;
            if(results.length == 0){
                // 
            }else{
                isKnownUser = true;
            }

            bot.api.users.info({user: message.user}, this.MULTI("userInfo"));

            // pass the same info to the next sync function             
            this.MULTI("params")(bot, message, callback, isKnownUser);
        },function(results){
            var bot = results.params[0],
                message = results.params[1],
                callback = results.params[2],
                isKnownUser = results.params[3],
                userInfo = results.userInfo;
        }
    );

I've noticed that I can't seem to maintain access to many both local and global variables & functions during each callback. For example, the global params in the first function() of the flow work as I want them to:

However, in the next callback these will return "undefined", so I have to maintain them by manually adding & storing them through a custom this.MULTI("params") call. I have to do this in each step of the flow. Is this really the right way of doing this, or have I missed something obvious? It doesn't seem right to manually maintain that each step.

Thanks