Created
March 5, 2020 01:41
-
-
Save aulisius/4478ba4d2ea872d35237f489f58498b9 to your computer and use it in GitHub Desktop.
Custom Promise Implementation
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 MPromise(executor) { | |
this.status = "PENDING"; | |
this.value = null; | |
this.then = ( | |
onFulfill = _ => _, | |
onReject = _ => { | |
throw _; | |
} | |
) => | |
new MPromise((res, rej) => { | |
try { | |
let handle = this.status === "SUCCESS" ? onFulfill : onReject; | |
res(handle(this.value)); | |
} catch (_) { | |
rej(_); | |
} | |
}); | |
this.catch = onReject => this.then(undefined, onReject); | |
setTimeout(() => | |
executor( | |
value => { | |
this.value = value; | |
this.status = "SUCCESS"; | |
}, | |
value => { | |
this.value = value; | |
this.status = "ERROR"; | |
} | |
) | |
); | |
return this; | |
} | |
// MPromise.resolve = _ => new MPromise((res, rej) => res(_)); | |
// MPromise.reject = _ => new MPromise((res, rej) => rej(_)); | |
// MPromise.resolve(5) | |
// .then(_ => _ * 10) | |
// .then(_ => { | |
// throw 2; | |
// }) | |
// .then(_ => console.log("thenable", _), e => console.error(e)) | |
// .then(_ => console.log("done")); | |
let a = new MPromise((res, rej) => { | |
console.log("A"); | |
setTimeout(() => console.log("B")); | |
}); | |
console.log("C"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment