Created
January 20, 2015 03:06
-
-
Save timdream/4b09efbf02d66900cef9 to your computer and use it in GitHub Desktop.
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
var SyncPromise = function(callback) { | |
this._resolveCallbacks = []; | |
this._rejectCallbacks = []; | |
var resolve = (function resolve(value) { | |
if (this.state !== 'pending') { | |
return; | |
} | |
this.state = 'fulfilled'; | |
var callback; | |
while (callback = this._resolveCallbacks.shift()) { | |
callback(); | |
} | |
this._resolveCallbacks = this._rejectCallbacks = null; | |
}).bind(this); | |
var reject = (function reject(error) { | |
if (this.state !== 'pending') { | |
return; | |
} | |
this.state = 'fulfilled'; | |
var callback; | |
while (callback = this._rejectCallbacks.shift()) { | |
callback(); | |
} | |
this._resolveCallbacks = this._rejectCallbacks = null; | |
}).bind(this); | |
callback(resolve, reject); | |
}; | |
SyncPromise.prototype.state = 'pending'; | |
SyncPromise.prototype.then = function(onFulfill, onReject) { | |
var nextResolve, nextReject; | |
var p = new SyncPromise(function(resolve, reject) { | |
nextResolve = resolve; | |
nextReject = reject; | |
}); | |
switch (this.state) { | |
case 'pending': | |
(typeof onFulfill === 'function') && | |
this._resolveCallbacks.push(onFulfill); | |
this._resolveCallbacks.push(nextResolve); | |
(typeof onReject === 'function') && | |
this._resolveCallbacks.push(onReject); | |
this._resolveCallbacks.push(nextReject); | |
break; | |
case 'fulfilled': | |
(typeof onFulfill === 'function') && onFulfill(); | |
nextResolve(); | |
break; | |
case 'rejected': | |
(typeof onReject === 'function') && onReject(); | |
nextReject(); | |
break; | |
} | |
return p; | |
}; | |
SyncPromise.prototype.catch = function(onReject) { | |
return this.then(null, onRject); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment