Created
June 25, 2021 14:50
-
-
Save rajatjain-21/339e1c52c5f957499ef73973da5a4236 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
function PromisePolyfill(executor) { | |
let onResolve, onReject; | |
let fulfilled = false, | |
rejected = false, | |
called = false, | |
value; | |
function resolve(v) { | |
fulfilled = true; | |
value = v; | |
if (typeof onResolve === "function") { | |
onResolve(value); | |
called = true; | |
} | |
} | |
function reject(reason) { | |
rejected = true; | |
value = reason; | |
if (typeof onReject === "function") { | |
onReject(value); | |
called = true; | |
} | |
} | |
this.then = function(callback) { | |
onResolve = callback; | |
if (fulfilled && !called) { | |
called = true; | |
onResolve(value); | |
} | |
return this; | |
} | |
this.catch = function (callback) { | |
onReject = callback; | |
if (rejected && !called) { | |
called = true; | |
onReject(value); | |
} | |
return this; | |
}; | |
try { | |
executor(resolve, reject); | |
} catch (error) { | |
reject(error); | |
} | |
} | |
PromisePolyfill.resolve = (val) => | |
new PromisePolyFill(function executor(resolve, _reject) { | |
resolve(val); | |
}); | |
PromisePolyfill.reject = (reason) => | |
new PromisePolyFill(function executor(resolve, reject) { | |
reject(reason); | |
}); | |
PromisePolyfill.all = (promises) => { | |
let fulfilledPromises = [], | |
result = []; | |
function executor(resolve, reject) { | |
promises.forEach((promise, index) => | |
promise | |
.then((val) => { | |
fulfilledPromises.push(true); | |
result[index] = val; | |
if (fulfilledPromises.length === promises.length) { | |
return resolve(result); | |
} | |
}) | |
.catch((error) => { | |
return reject(error); | |
}) | |
); | |
} | |
return new PromisePolyFill(executor); | |
}; | |
const promise = new PromisePolyfill((resolve, reject) => { | |
console.log("Rajat"); | |
setTimeout(() => reject(42), 100) | |
}) | |
promise.then(val => console.log(val)).catch(error => console.log(error)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment