JSFiddle - React, Tailwind, and code Playground

by cancerbero_sgx

HTML

StatementBlock - doing asynch task synchronously using jquery promises.

JavaScript

/* 
StatementBlock - resolves the problem of executing synchronously (execute the following only after the previous task has ended) 
several asynchronous tasks like ajax, wait for user events or element existense. Based on jquery promises. 
*/
var ns = {}
ns.StatementBlock = function(){
	this.statements = []; 
}
ns.StatementBlock.prototype._wrap = function(fn) {
	var self=this;
	var wrapper = function(){
		var promise = jQuery.Deferred();
		if(fn)
			fn(promise); 
		return promise; 
	}
	return wrapper;
}
ns.StatementBlock.prototype._getNextStatement = function(){
	if(!this.statements.length)
		return null
	var ret = this.statements.splice(0, 1);
	return ret[0]; 
}
/** @return a function that perform the statemetn and return a promise */
ns.StatementBlock.prototype._execNext = function() {
	var self=this;
	var nextStatement = this._getNextStatement();
	var wrap = this._wrap(nextStatement);
	var promise = wrap(); //execute it!
	promise.done(function(){ self._execNext(); })
	return wrap; 
}
/** @return a function that perform the statemetn and return a promise */
ns.StatementBlock.prototype.exec = function(){
	if(!this.statements.length)
		return ;
	return this._execNext(); 
}
ns.StatementBlock.prototype.append = ns.StatementBlock.prototype.add = function(fn) {
	this.statements.push(fn); 
}

//test
var block1 = new ns.StatementBlock(); 
block1.add(function(job){setTimeout(function(){job.resolve();console.log('job 1 done'); }, 1000) }); 
block1.add(function(job){setTimeout(function(){job.resolve();console.log('job 2 done');}, 1000) }); 
block1.add(function(job){setTimeout(function(){job.resolve();console.log('job 3 done');}, 1000) }); 
block1.add(function(job){setTimeout(function(){job.resolve();console.log('job 4 done');}, 1000) }); 
block1.exec();