Skip to content

Instantly share code, notes, and snippets.

@cyan33
Created October 14, 2017 00:08
Show Gist options
  • Save cyan33/9d2c4dac2744b7fdb3999643fee3c886 to your computer and use it in GitHub Desktop.
Save cyan33/9d2c4dac2744b7fdb3999643fee3c886 to your computer and use it in GitHub Desktop.
A simple promise implementation
// https://medium.com/gitconnected/understand-javascript-promises-by-building-a-promise-from-scratch-84c0fd855720
class SimplePromise {
constructor(executionFunction) {
this.promiseChain = [];
this.handleError = () => {};
this.onResolve = this.onResolve.bind(this);
this.onReject = this.onReject.bind(this);
executionFunction(this.onResolve, this.onReject)
}
then(onResolve) {
this.promiseChain.push(onResolve)
return this
}
onResolve(value) {
let storedValue = value
try {
this.promiseChain.forEach(nextFunction => {
storedValue = nextFunction(storedValue)
})
} catch(err) {
this.promiseChain = []
this.onReject(error)
}
}
catch(errorHandler) {
this.handleError = errorHandler
return this
}
onReject(error) {
this.handleError(error)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment