Skip to content

Instantly share code, notes, and snippets.

@treyhuffine
Last active November 2, 2022 13:21
Show Gist options
  • Save treyhuffine/d2e63bdee6645a7a0619989ee5a4538b to your computer and use it in GitHub Desktop.
Save treyhuffine/d2e63bdee6645a7a0619989ee5a4538b to your computer and use it in GitHub Desktop.
A simple JavaScript Promise implementation for education purposes
class PromiseSimple {
constructor(executionFunction) {
this.promiseChain = [];
this.handleError = () => {};
this.onResolve = this.onResolve.bind(this);
this.onReject = this.onReject.bind(this);
executionFunction(this.onResolve, this.onReject);
}
then(handleSuccess) {
this.promiseChain.push(handleSuccess);
return this;
}
catch(handleError) {
this.handleError = handleError;
return this;
}
onResolve(value) {
let storedValue = value;
try {
this.promiseChain.forEach((nextFunction) => {
storedValue = nextFunction(storedValue);
});
} catch (error) {
this.promiseChain = [];
this.onReject(error);
}
}
onReject(error) {
this.handleError(error);
}
}
@ahmadseder
Copy link

ahmadseder commented Dec 29, 2017

@sudo-suhas
I think we need to pass the initialValue

onResolve(value) {
    try {
      return this.promiseChain.reduce(
        (result, nextFunction) => nextFunction(result)
      ,value);
    } catch (error) {
      this.promiseChain = [];

      this.onReject(error);
    }
  }

@treyhuffine
Copy link
Author

Full walkthrough along with video explanation here: https://skilled.dev/course/build-a-javascript-promise

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment