-
-
Save cnanders/ed2929a142f984d942e97f6ac62c8a10 to your computer and use it in GitHub Desktop.
A simple JavaScript Promise implementation for education purposes
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
class PromiseSimple { | |
constructor(executionFunction) { | |
this.promiseChain = []; | |
this.handleError = () => {}; | |
this.onResolve = this.onResolve.bind(this); | |
this.onReject = this.onReject.bind(this); | |
// executing this function either calls this.onResolve | |
// or this.onReject | |
executionFunction(this.onResolve, this.onReject); | |
} | |
then(onResolve) { | |
// appends provided function to the promiseChain list of this class | |
// and returns the class instance | |
this.promiseChain.push(onResolve); | |
return this; | |
} | |
catch(handleError) { | |
// sets the handleError method of this class to | |
// the provided function and returns the class instance | |
this.handleError = handleError; | |
return this; | |
} | |
onResolve(value) { | |
let storedValue = value; | |
try { | |
// every call of the .then() method on the promise | |
// passes in a function that is appended to this.promiseChain | |
// here we loop through the list of functions in this.promiseChain, | |
// execute it, using the return of the execution as the input to | |
// the next function in the list. | |
// | |
// Can also be done with reduce | |
/* | |
this.promiseChain.reduce( | |
(valReduced, nextFcn) => nextFcn(valReduced), // return of nextFcn execution is input of next call | |
value // initial value | |
) | |
*/ | |
this.promiseChain.forEach((nextFunction) => { | |
storedValue = nextFunction(storedValue); | |
}); | |
} catch (error) { | |
this.promiseChain = []; | |
this.onReject(error); | |
} | |
} | |
onReject(error) { | |
// calls this.handleError, which is set when the user calls the catch() method | |
this.handleError(error); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment