Skip to content

Instantly share code, notes, and snippets.

@gs-akhan
Created April 22, 2014 20:04
Show Gist options
  • Save gs-akhan/11192445 to your computer and use it in GitHub Desktop.
Save gs-akhan/11192445 to your computer and use it in GitHub Desktop.
Dirty Promise Pattern
var Promise = function(inst) {
if (inst instanceof Promise) {
return inst;
}
else {
this.promises = [];
return this;
}
};
Promise.prototype.execute = function(fn) {
this.promises.push(fn);
this.resolve();
return this;
};
Promise.prototype.resolve = function(first_argument) {
// body...
if(this.promises.length === 0) {
this.done();
}
this.promises.shift().call();
};
Promise.prototype.then = function(fn) {
this.promises.push(fn);
return this;
};
Promise.prototype.done = function(fn) {
fn.call();
};
/*
* Three function to simulate Async nature..
*/
function a() {
var pro = new Promise(promiseInst)
setTimeout(function() {
console.log('excecutin A');
pro.resolve();
},2000);
}
function b() {
var pro = new Promise(promiseInst)
setTimeout(function() {
console.log('excecutin B');
pro.resolve();
},2000);
};
function c() {
var pro = new Promise(promiseInst);
setTimeout(function() {
console.log('excecutin C');
pro.resolve();
},2000);
};
//Lets test it out..
var promiseInst = new Promise();
promiseInst.execute(a)
.then(b)
.then(c)
.then(function() {
console.log('WE ARE DONE');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment