Created
June 15, 2023 07:43
-
-
Save Sidd27/54575767a56cc68f14ee00a533762954 to your computer and use it in GitHub Desktop.
Custom Promise Implementation in Javascript
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 MyPromise(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); | |
} | |
} | |
MyPromise.resolve = (val) => | |
new MyPromise(function executor(resolve, _reject) { | |
resolve(val); | |
}); | |
MyPromise.reject = (reason) => | |
new MyPromise(function executor(resolve, reject) { | |
reject(reason); | |
}); | |
MyPromise.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 MyPromise(executor); | |
}; | |
const promise = new MyPromise((resolve, _reject) => { | |
console.log("Promisessssss!!!!!"); | |
setTimeout(() => resolve(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