Last active
August 28, 2022 06:16
-
-
Save vijayprwyd/b4085418fb3947076a365056cd77550b 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
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); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment