Last active
February 5, 2025 09:26
-
-
Save abhinavnigam2207/cb344fddfa86fc952d9a0bcd9811548f to your computer and use it in GitHub Desktop.
Promise Polyfill
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
// Polyfill for Promise() | |
// ----------------------------- | |
// Syntax Example | |
// const p = new myPromise(resolve, reject); | |
const myPromise = function (executer) { | |
let onResolve, onReject, | |
isFulfilled = false, | |
isCalled = false, | |
value; | |
function resolve(val) { | |
isFulfilled = true; | |
value = val | |
if (typeof onResolve === 'function') { | |
onResolve(val); | |
isCalled = true; | |
} | |
} | |
function reject(value) { | |
onReject(value); | |
} | |
this.then = function(callback) { | |
onResolve = callback; | |
if (isFulfilled && !isCalled) { | |
isCalled = true; | |
onResolve(value); | |
} | |
return this; | |
}, | |
this.catch = function(callback) { | |
onReject = callback; | |
if (isFulfilled && !isCalled) { | |
isCalled = true; | |
onReject(value); | |
} | |
return this; | |
} | |
try { | |
executer(resolve, reject); | |
} catch (error) { | |
reject(error); | |
} | |
}; | |
const promise1 = new myPromise((resolve, reject) => { | |
setTimeout(() => { | |
resolve('success'); | |
}, 4000); | |
}); | |
promise1.then((resp)=> { | |
console.log(resp); | |
}).catch((err)=> { | |
console.log(err); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment