Created
August 13, 2017 18:37
-
-
Save flapenguin/40c9a4d05faed068b488c490cd357732 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
function nextTick(callback) { | |
setTimeout(callback, 0); | |
} | |
class Promise { | |
constructor(callback) { | |
this.state = 'pending'; | |
this.onSuccess = []; | |
callback(value => { | |
this.state = 'resolved'; | |
this.value = value; | |
this.onSuccess.forEach(callback => callback(value)); | |
}); | |
} | |
then(callback) { | |
return new Promise(resolve => { | |
if (this.state === 'resolved') { | |
nextTick(() => resolve(callback(this.value))); | |
} else { | |
this.onSuccess.push(value => resolve(callback(value))); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment