Chainable Async Functions

Small utility function demonstrated to create chainable async functions that wait for one another to execute.

by IPWright83

HTML

<pre id="log"></pre>

JavaScript

var q = function(f, pF) {
		f = f || function(callback) { callback() ; };
    return {
        then: function(callback) {
        		console.log(this);
            return q(callback, this)   
        },
        done: function(callback) {
        		callback = callback || function() {};
            if(pF) { pF.done(function() { f(callback); }); }
            else { f(callback); }           
        }
    }
};

// First Technique for calling q
var a = function(callback) { document.getElementById("log").innerHTML += "waiting 2500ms\n"; setTimeout(callback, 2500); };
var b = function(callback) { document.getElementById("log").innerHTML += "waiting 1500ms\n"; setTimeout(callback, 1500); };
var c = function(callback) { document.getElementById("log").innerHTML += "waiting 3000ms\n"; setTimeout(callback, 3000); };
var d = function() { document.getElementById("log").innerHTML += "Finished"; };

// Note that this can be written in different ways, the following would also be correct
//q(a).then(b).then(c).done(d);
var works = function() {
	var k = q().then(a).then(b).then(c).then(d);
	k.done();
};

var doesntWork = function() {
	var k = q();
	k.then(a).then(b).then(c).then(d);
	k.done();
};

doesntWork();