Last active
November 17, 2021 16:01
-
-
Save lior-amsalem/c54517790d6672b2bfa892249895e1d3 to your computer and use it in GitHub Desktop.
For educational purpose, here we have a custom made promise handler.
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
/** | |
This is for educational purpose only and for fun. | |
*/ | |
class customPromise { | |
constructor(functionToResolve) { | |
this.status = "pending"; | |
this.onFulfilledCallbacks = []; | |
this.onRejectedCallbacks = []; | |
const resolve = (value) => { | |
console.log("resolve"); // console logs are for learinng purposes | |
if (this.status === "pending") { | |
this.status = "fulfilled"; | |
this.value = value; | |
this.onFulfilledCallbacks.forEach((fn) => fn(value)); | |
} | |
}; | |
const reject = (value) => { | |
console.log("reject"); | |
if (this.status === "pending") { | |
this.status = "rejected"; | |
this.value = value; | |
this.onRejectedCallbacks.forEach((fn) => fn(value)); | |
} | |
}; | |
try { | |
functionToResolve(resolve, reject); | |
} catch (err) { | |
reject(err); | |
} | |
} | |
then(onFulfilled, onRejected) { | |
return new customPromise((resolve, reject) => { | |
if (this.status === "pending") { | |
console.log( | |
"push functions to array before executing them!", | |
onFulfilled, | |
onRejected | |
); | |
this.onFulfilledCallbacks.push(() => { | |
try { | |
const fulfilledLastPromise = onFulfilled(this.value); | |
resolve(fulfilledLastPromise); | |
} catch (err) { | |
reject(err); | |
} | |
}); | |
this.onRejectedCallbacks.push(() => { | |
try { | |
const rejectedLastPromise = onRejected(this.value); | |
reject(rejectedLastPromise); | |
} catch (err) { | |
reject(err); | |
} | |
}); | |
} | |
if (this.status === "fulfilled") { | |
try { | |
const fulfilledLastPromise = onFulfilled(this.value); | |
resolve(fulfilledLastPromise); | |
} catch (err) { | |
reject(err); | |
} | |
} | |
if (this.status === "rejected") { | |
try { | |
const rejectedLastPromise = onRejected(this.value); | |
resolve(rejectedLastPromise); | |
} catch (err) { | |
reject(err); | |
} | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment