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) {
            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);
q().then(a).then(b).then(c).then(d).done();

// Calling q within a loop
var loop = q();
for(let i = 0; i < 5; i++) {
	loop = loop.then((callback) => {
  	setTimeout(() => { console.log(i); callback(); }, 1000);
  });
}
loop.done();