Skip to content

Instantly share code, notes, and snippets.

@timdream
Created January 20, 2015 03:06
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 timdream/4b09efbf02d66900cef9 to your computer and use it in GitHub Desktop.
Save timdream/4b09efbf02d66900cef9 to your computer and use it in GitHub Desktop.
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