Last active
December 16, 2020 03:44
-
-
Save daovietanh190499/85b6bce92c53e2b8f366b0e2dac58adb 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
class CustomPromise { | |
constructor(executable = (resolve, reject) => {}) { | |
this.state = 'pending'; | |
this.result = undefined; | |
this.error = undefined; | |
this.thenList = []; | |
this.catchList = []; | |
this.executable = executable; | |
this.execute(); | |
return this | |
} | |
execute() { | |
try { | |
this.executable(this.resolve.bind(this), this.reject.bind(this)); | |
} catch(err) { | |
this.reject(err); | |
} | |
} | |
reject(reason) { | |
this.state = 'rejected'; | |
this.error = reason; | |
this.catchList.map(promise => { | |
promise.execute(); | |
}) | |
this.thenList.map(promise => { | |
promise.execute(); | |
}) | |
} | |
resolve(result) { | |
this.result = result; | |
if(! (this.result instanceof CustomPromise) && ! (this.result instanceof Promise)) { | |
this.state = 'fulfilled'; | |
this.thenList.map(promise => { | |
promise.execute(); | |
}) | |
} else { | |
this.executable = (resolve, reject) => { | |
this.result.then(result => {resolve(result)}).catch(error=> {reject(error)}) | |
} | |
this.execute() | |
} | |
} | |
then(thenHandler) { | |
let promise =new CustomPromise((resolve, reject) => { | |
if (this.state === 'rejected') throw new Error(this.error) | |
if (this.state === 'fulfilled') { | |
let result = thenHandler(this.result) | |
resolve(result) | |
} | |
}) | |
this.thenList.push(promise); | |
return promise | |
} | |
catch(catchHandler) { | |
let promise = new CustomPromise((resolve, reject) => { | |
if(this.state === 'rejected') { | |
catchHandler(this.error) | |
resolve() | |
} | |
}) | |
this.catchList.push(promise); | |
return this | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment