Last active
September 17, 2018 03:23
-
-
Save qianbin/0a3560582c5a66e2c197a95dace8d3ce 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
import Deferred from '@/base/deferred' | |
class PromiseTracker { | |
private readonly deferred = new Deferred() | |
constructor() { | |
this.deferred.catch() | |
} | |
public track<T extends object>(obj: T): T { | |
return this._track(obj) | |
} | |
public rejectAll() { | |
this.deferred.reject('rejected by tracker') | |
} | |
private _track(obj: any): any { | |
const _this = this | |
return new Proxy(obj, { | |
get(target, key, receiver) { | |
return _this._track(Reflect.get(target, key, receiver)) | |
}, | |
apply(target, thisArg, argArray) { | |
const ret = Reflect.apply(target, thisArg, argArray) | |
if (ret instanceof Promise) { | |
const d = new Deferred() | |
ret.then(r => { | |
d.resolve(_this._track(r)) | |
}).catch(err => { | |
d.reject(_this._track(err)) | |
}) | |
_this.deferred | |
.catch(err => { | |
d.reject(_this._track(err)) | |
}) | |
return _this._track(d.then()) | |
} | |
return _this._track(ret) | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment