Last active
September 8, 2023 08:47
-
-
Save carefree-ladka/c8c91a70490105a9a6a714a723e7266c to your computer and use it in GitHub Desktop.
Promise Polyfill
This file contains hidden or 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
| /* | |
| Author: Pawan Kumar | |
| Date : 04/28/2023 | |
| Location: Bangalore, India | |
| */ | |
| class MyPromise { | |
| constructor(executor) { | |
| let resolved = false; | |
| let rejected = false; | |
| let resolveValue; | |
| let rejectValue; | |
| let resolveCallbacks = []; | |
| let rejectCallbacks = []; | |
| function resolve(value) { | |
| if (resolved || rejected) return; | |
| resolved = true; | |
| resolveValue = value; | |
| resolveCallbacks.forEach((fn) => fn(value)); | |
| } | |
| function reject(reason) { | |
| if (resolved || rejected) return; | |
| rejected = true; | |
| rejectValue = reason; | |
| rejectCallbacks.forEach((fn) => fn(reason)); | |
| } | |
| this.then = function (onResolve, onReject) { | |
| if (resolved) { | |
| onResolve(resolveValue); | |
| } else if (rejected) { | |
| onReject(rejectValue); | |
| } else { | |
| resolveCallbacks.push(onResolve); | |
| rejectCallbacks.push(onReject); | |
| } | |
| return this; | |
| }; | |
| this.catch = function (onReject) { | |
| if (rejected) { | |
| onReject(rejectValue); | |
| } else { | |
| rejectCallbacks.push(onReject); | |
| } | |
| return this; | |
| }; | |
| this.finally = function (cb) { | |
| return this.then( | |
| (value) => { | |
| cb(); | |
| return value; | |
| }, | |
| (reason) => { | |
| cb(); | |
| throw reason; | |
| } | |
| ); | |
| }; | |
| executor(resolve, reject); | |
| } | |
| } | |
| const promise = new MyPromise((resolve, reject) => { | |
| setTimeout(() => { | |
| resolve("foo"); | |
| }, 300); | |
| }); | |
| promise | |
| .then((data) => console.log("data-->", data)) | |
| .catch((e) => console.log("error-->", e)); | |
| //data--> foo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment