Skip to content

Instantly share code, notes, and snippets.

@daovietanh190499
Last active December 16, 2020 03:44
Show Gist options
  • Save daovietanh190499/85b6bce92c53e2b8f366b0e2dac58adb to your computer and use it in GitHub Desktop.
Save daovietanh190499/85b6bce92c53e2b8f366b0e2dac58adb to your computer and use it in GitHub Desktop.
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