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();
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.