javascriptasynchronouscloudparse-platform

Shared variables in asynchronous function calls


Is there a basic way to share a variable between two asynchronous functions in Javascript? I'm writing a function for my Parse.com application that sends two queries concurrently and the second waits on the results of the former. I've been using a basic shared boolean and a busy-wait loop, but the loop does not terminate if the boolean value was not set before the start of the loop (but does if it was set before, so the state is in fact being shared across the two callbacks). This makes me think that I need some form of a "volatile" variable but it does not seem that this exists in Javascript, seeing as there are not really threading capabilities/optimizations like this. If it helps, I've added some abbreviated code to help explain what I'm doing:

    var firstQueryDone = false;
    var firstResultsError = false;
    var foundUser;
    var foundFollowers;

    ...
    [put some constraints on the query]
    ...

    followersQuery.first({
        success: function(followers) {

            ....

            firstQueryDone = true;
        },
        error: function(error) {
            firstResultsError = true;
            response.error(error);
        }
    });


    .....
    [constraints on new query]
    .....

    commentsQuery.find({
        success: function(comments) {
            while(!firstQueryDone && !firstResultsError);
            if(!firstResultsError) {
                .....
            } else {
                ......
            }
        },
        error: function(error) {
            response.error(error);
        }
    });

Solution

  • I wouldn't use a busy wait-loop. Instead, have both success and error callbacks call store their state then call an external method that handles.

    var fComplete = false,
        sComplete = false,
        didError = false;
    
    
    #.first(
        success: function () {
            fComplete = true;
            checkMethod();
        },
        error: function() {
            fComplete = true;
            didError = true;
            checkMethod();
        }
    );
    #.second(
        success: function() {
            sComplete = true;
            checkMethod();
        },
        error: function() {
            sComplete = true;
            didError = true;
            checkMethod();
        }
    );
    
    function checkMethod() {
        if(fComplete && sComplete) {
            if(didError) {
                //Handle error
            } else {
                //Do success here
            }
        }
    }
    

    This way, you don't have a wait loop hogging some resources, and you simply have state changes and onStateChange events.