Last active
August 29, 2015 14:16
-
-
Save A1rPun/2838fade409aee33fca4 to your computer and use it in GitHub Desktop.
Customizable Promise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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