Skip to content

Instantly share code, notes, and snippets.

@flapenguin
Created August 13, 2017 18:37
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 flapenguin/40c9a4d05faed068b488c490cd357732 to your computer and use it in GitHub Desktop.
Save flapenguin/40c9a4d05faed068b488c490cd357732 to your computer and use it in GitHub Desktop.
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