Last active
August 29, 2015 13:57
-
-
Save jeffbcross/9905075 to your computer and use it in GitHub Desktop.
Quick Async Promise Hack
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 orderOfExecution = []; | |
function mockResolve_ (promise, resolvedVal, rejectedVal) { | |
promise.resolvedVal = resolvedVal; | |
promise.rejectedVal = rejectedVal; | |
} | |
function flush (promise) { | |
promise.resolveNext_.call(promise); | |
}; | |
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_(); | |
} | |
var p = new Promise(function (resolve, reject) { | |
resolve('10 seconds later'); | |
}). | |
then(function() { | |
orderOfExecution.push('thenResolve'); | |
}); | |
mockResolve_(p, 'value'); | |
flush(p); | |
orderOfExecution.push('postFlush'); | |
if (orderOfExecution[0] === 'thenResolve' && orderOfExecution[1] === 'postFlush') { | |
console.log('Synchronous execution!'); | |
} | |
else { | |
console.log('Execution was NOT synchronous'); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment