Last active
February 22, 2023 21:33
-
-
Save thearunkumar/2bf8288a82b0f71d9f971afb79c070b5 to your computer and use it in GitHub Desktop.
Custom Promise using vanilla js
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 CustomPromise { | |
// Takes the callback methods of `.then` | |
thenQueue = []; | |
// Catch callback | |
catchCallBack = null; | |
// Finally callback | |
finallyCallback = null; | |
// executableMethod takes the resolve, reject arguments as its parameters. | |
constructor(exectableMethod) { | |
if (typeof exectableMethod !== "function") { | |
throw new Error("function is not provided in the arguments. exiting."); | |
} | |
function resolve(data) { | |
this.state = "fulfilled"; | |
this.result = data; | |
let value = data; | |
this.thenQueue.forEach((method) => { | |
if (typeof method === "function") { | |
value = method.call(null, value); | |
} | |
}); | |
handleFinally.call(this); | |
} | |
function reject(err) { | |
this.state = "fulfilled"; | |
if (typeof this.catchCallback === "function") { | |
this.catchCallback.call(null, err); | |
} | |
handleFinally.call(this); | |
} | |
function handleFinally() { | |
if (typeof this.finallyCallback === "function") { | |
this.finallyCallback.call(null); | |
} | |
} | |
// This is critical as we need to bind the `resolve` | |
// and the `reject` methods to our internal methods | |
// for us to be able to access whenever the promise | |
// is either resolved or rejected from the code by the user. | |
exectableMethod.call(null, resolve.bind(this), reject.bind(this)); | |
} | |
then(thenCallback) { | |
this.thenQueue.push(thenCallback); | |
return this; | |
} | |
catch(catchCallback) { | |
this.catchCallback = catchCallback; | |
return this; | |
} | |
finally(finallyCallback) { | |
this.finallyCallback = finallyCallback; | |
} | |
} | |
// Setting some defaults. | |
CustomPromise.prototype.state = "pending"; | |
CustomPromise.prototype.result = undefined; | |
// const customPromise = new CustomPromise((res, rej) => { | |
// setTimeout(() => { | |
// res("Hey"); | |
// }, 2000); | |
// }); | |
// customPromise | |
// .then((data) => { | |
// console.log("First then", data); | |
// }) | |
// .then((data) => { | |
// console.log("Second then", data); | |
// }) | |
// .then((data) => { | |
// console.log("Third then", data); | |
// }) | |
// .catch((err) => { | |
// console.log("Catch", err); | |
// }) | |
// .finally(() => { | |
// console.log("Finally"); | |
// }); | |
export default CustomPromise; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment