Skip to content

Instantly share code, notes, and snippets.

@rohanBagchi
Created October 3, 2020 10:38
Show Gist options
  • Save rohanBagchi/cbcbabd037e9c3e3edc7fae9e8f5c605 to your computer and use it in GitHub Desktop.
Save rohanBagchi/cbcbabd037e9c3e3edc7fae9e8f5c605 to your computer and use it in GitHub Desktop.
export function CustomPromise(executorFn) {
const PossibleStates = {
PENDING: 'PENDING',
RESOLVED: 'RESOLVED',
REJECTED: 'REJECTED',
};
let currentSuccessResult;
let currentFailureResult;
const listOfSuccessCallbacks = [];
const listOfFailureCallbacks = [];
let currentState = PossibleStates.PENDING;
this.then = (callbackFunction) => {
listOfSuccessCallbacks.push(callbackFunction);
return this;
};
this.catch = (callbackFunction) => {
listOfFailureCallbacks.push(callbackFunction);
return this;
};
const resolve = (resolvedValue) => {
if (currentState !== PossibleStates.PENDING) return;
currentSuccessResult = resolvedValue;
listOfSuccessCallbacks.forEach((callbackFunction) => {
currentSuccessResult = callbackFunction(currentSuccessResult);
});
currentState = PossibleStates.RESOLVED;
};
const reject = (rejectedValue) => {
if (currentState !== PossibleStates.PENDING) return;
currentFailureResult = rejectedValue;
listOfSuccessCallbacks.forEach((callbackFunction) => {
currentFailureResult = callbackFunction(currentFailureResult);
});
currentState = PossibleStates.REJECTED;
};
executorFn(resolve, reject);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment