Skip to content

Instantly share code, notes, and snippets.

@samholmes
Last active April 16, 2020 22:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samholmes/5596262 to your computer and use it in GitHub Desktop.
Save samholmes/5596262 to your computer and use it in GitHub Desktop.
Discussion on how to write a parallel asynchronous routine using plain, vanilla JS.

Parallel Async Patterns in Vanilla JS

function routine(){
    var counter = 3;
    
    asyncThing(function(){
        // Do stuff
        
        done();
    })
    asyncThing(function(){
        // Do stuff
        
        done();
    })
    asyncThing(function(){
        // Do stuff
        
        done();
    })

    function done(){
        if (--counter)
            return;
        
        // Complete the routine
    }
}

Above is an example of a routine that does three asynchronous sub-routines, and then completes with the done function after all asynchronous things have finished. This is using pure vanilla JavaScript. Keeping with vanilla JS, how could you improve this pattern? Are there any patterns that I'm not aware of that are arguably better?

Please provide useful discussion in the comments.

Edit

What if you wrote an ad-hoc finisher function like this:

var finisher = function(finish){
    var counter = 0;
    return function(f){
        ++counter;
        return function(){
            f.apply(this, arguments);
            if (!--counter)
                finish();
        };
    }
}

// Now your routine would look like this

function routine(){
    var wrap = finisher(done);
    
    asyncThing(wrap(function(){
        // Do stuff
    }))
    asyncThing(wrap(function(){
        // Do stuff
    }))
    asyncThing(wrap(function(){
        // Do stuff
    }))

    function done(){
        // Complete the routine
    }
}

But this quickly becomes a library. Albeit a small lib, still a dependency. Thoughts?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment