Skip to content

Instantly share code, notes, and snippets.

@A1rPun
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save A1rPun/2838fade409aee33fca4 to your computer and use it in GitHub Desktop.
Save A1rPun/2838fade409aee33fca4 to your computer and use it in GitHub Desktop.
Customizable Promise
function Promise(o, fnNames){
fnNames = fnNames || ['done', 'fail', 'always'];
var done = fnNames[0],
fail = fnNames[1],
always = fnNames[2];
o.states = { none: 0 };
o.states[done] = 1;
o.states[fail] = 2;
o.handleState = function(){
if(!this.state) return;
var i, l;
if(this.state === this.states[done]){
for(i = 0, l = this[done].callbacks.length; i < l ; i++){
this[done].callbacks[i]();
}
} else if(this.state === this.states[fail]){
for(i = 0, l = this[fail].callbacks.length; i < l ; i++){
this[fail].callbacks[i]();
}
}
for(i = 0, l = this[always].callbacks.length; i < l ; i++){
this[always].callbacks[i]();
}
};
o.state = 0;
o[done] = function(cb){
if(this.state === this.states[done]) cb();
else this[done].callbacks.push(cb);
return this;
};
o[done].callbacks = [];
o[fail] = function(cb){
if(this.state === this.states[fail]) cb();
else this[fail].callbacks.push(cb);
return this;
};
o[fail].callbacks = [];
o[always] = function(cb){
if(this.state) cb();
else this[always].callbacks.push(cb);
return this;
};
o[always].callbacks = [];
return o;
}
//Normal object wrapper
var someObj = {
itisdone:function(){
this.state = this.states.done;
this.handleState();
}
},
promise = (new Promise(someObj))
.done(function(){console.log('done')})
.fail(function(){console.log('fail')})
.always(function(){console.log('always')})
.itisdone();
//XHR Wrapper
var xhr = new XMLHttpRequest(),
request = new Promise(xhr, ['success', 'error', 'finally']);
request.onload = function(){
this.state = this.status >= 200 && this.status < 400 ? this.states.done : this.states.fail;
this.handleState();
};
request
.success(function(){console.log('success')})
.error(function(){console.log('error')})
.finally(function(){console.log('finally')});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment