Skip to content

Instantly share code, notes, and snippets.

@jeffbcross
Created April 1, 2014 20:30
Show Gist options
  • Save jeffbcross/9922513 to your computer and use it in GitHub Desktop.
Save jeffbcross/9922513 to your computer and use it in GitHub Desktop.
Basic ES6 Promise.then synchronous monkey patch
Promise.prototype.then = function (good, bad) {
this.chain_ = this.chain_ || [];
this.chain_.push({resolve: good, reject: bad});
return this;
}
Promise.prototype.resolveNext_ = function () {
if (!this.chain_) return;
var next = this.chain_.shift(), nextVal;
if (!next) return;
if (this.resolvedVal) {
next = next.resolve;
}
else {
next = next.reject;
}
nextVal = next ? next.call(this, this.resolvedVal) : null;
nextVal && this.resolveNext_();
}
it('should resolve synchronously', function() {
var orderOfExecution = [],
p = new Promise(function (resolve, reject) {
//Nothing in here does anything.
});
p.then(function() {
orderOfExecution.push('thenResolve');
});
mockResolve_(p, 'value');
flush(p);
orderOfExecution.push('postFlush');
expect(orderOfExecution[0]).toBe('thenResolve');
expect(orderOfExecution[1]).toBe('postFlush');
expect(orderOfExecution[2]).toBeUndefined();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment