Created
July 19, 2023 06:24
-
-
Save mayank-shekhar/020e5669be53e281e7e701312a9cc9a3 to your computer and use it in GitHub Desktop.
Simple polyfill for JavaScript Promise class
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 CustomPromise (executor) { | |
let onResolve; | |
let onReject; | |
let isFulfilled = false; | |
let isRejected = false; | |
let isCalled = false; // indicates callback has been called | |
let value; let error; | |
function resolve(val) { | |
isFulfilled = true; | |
value = val; | |
if (typeof onResolve === 'function' && ! isCalled) { | |
onResolve (val); | |
isCalled = true; | |
} | |
} | |
function reject(err) { | |
isRejected = true; | |
error = err; | |
if (typeof onReject === 'function' && !isCalled) { | |
onReject(err); | |
isCalled = true; | |
} | |
} | |
this.then = function (thenHandler) { | |
onResolve = thenHandler; | |
if (isCalled && isFulfilled) { | |
onResolve(value); | |
isCalled = true; | |
} | |
return this; | |
}; | |
this.catch = function (catchHandler) { | |
onReject = catchHandler; | |
if (!isCalled && isRejected) { | |
onReject(error); | |
isCalled = true; | |
} | |
return this; | |
} | |
executor( resolve, reject); | |
} |
Author
mayank-shekhar
commented
Jul 19, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment