Created
October 3, 2020 10:38
-
-
Save rohanBagchi/cbcbabd037e9c3e3edc7fae9e8f5c605 to your computer and use it in GitHub Desktop.
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
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