Skip to content

Instantly share code, notes, and snippets.

@k10526
Last active August 13, 2019 00:02
Show Gist options
  • Save k10526/a286f0b8cfbc2d28a846c10cccba272e to your computer and use it in GitHub Desktop.
Save k10526/a286f0b8cfbc2d28a846c10cccba272e to your computer and use it in GitHub Desktop.
AbortablePromise
class AbortablePromise{
constructor(fn, parent) {
this._reject;
this._aborted = false;
this._parent = parent;
this._promise = Promise.race([
new Promise((res, rej) => {
this._reject = rej;
}),
new Promise(fn)
])
.then((res) => res);
}
abort() {
if (this._parent) {
this._parent.abort();
}
this._reject({aborted: true});
}
toPromise() {
return this._promise;
}
then(fn1, fn2) {
return new AbortablePromise((res, rej) => {
return this.toPromise().then(fn1, fn2).then(res, rej);
}, this);
}
catch(fn) {
return new AbortablePromise((resolve, reject) => {
return this.toPromise().catch(res => {
if (res && res.aborted) {
return Promise.reject(res);
}
return fn(res);
}).then(resolve, reject);
}, this);
}
finally(fn) {
return new AbortablePromise((res, rej) => {
return this.toPromise().finally(fn).then(res, rej);
}, this);
}
}
const delay = () => new Promise(res => setTimeout(()=> {res("delay")}, 5000));
// promise
const p = new AbortablePromise((res, rej) => res("aa"))
.then(() => {console.log(1); return Promise.reject(123)})
.catch((res) => {console.log(res);console.log("error")})
.then(() => {console.log(2); return delay()})
.then((res) => {console.log(res);console.log(3); return delay()})
.then(() => {console.log(4); return delay()})
.then(() => {console.log(5); return delay()})
.then(() => {console.log(6); return delay()})
.finally(()=> {console.log("end")});
console.log(p) // p.abort();
// async / await
const fn = async () => {
p2 = new AbortablePromise((res, rej) => {return delay().then(res)});
await p2;
console.log(2)
}
fn();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment