如何实现扩展Promise的延期承诺?将Promise扩展为类型安全的用途是非常重要的,而且需要典型的Promise。
实施后
export class Deferred<T> extends Promise<T> {
public _resolveSelf;
public _rejectSelf;
constructor() {
super(
(resolve, reject) =>
{
this._resolveSelf = resolve
this._rejectSelf = reject
}
)
}
public resolve(val:T) { this._resolveSelf(val) }
public reject(reason:any) { this._rejectSelf(reason) }
}
抛出TypeError: _this is undefined
。
在this Typescript playground中,可以看到已编译的javascript很有趣。在第15行中,在声明_this
期间已经分配了其属性。
答案 0 :(得分:1)
export class Deferred<T> implements Promise<T> {
private _resolveSelf;
private _rejectSelf;
private promise: Promise<T>
constructor() {
this.promise = new Promise( (resolve, reject) =>
{
this._resolveSelf = resolve
this._rejectSelf = reject
}
)
}
public then<TResult1 = T, TResult2 = never>(
onfulfilled?: ((value: T) =>
TResult1 | PromiseLike<TResult1>) | undefined | null,
onrejected?: ((reason: any) =>
TResult2 | PromiseLike<TResult2>) | undefined | null
): Promise<TResult1 | TResult2> {
return this.promise.then(onfulfilled, onrejected)
}
public catch<TResult = never>(
onrejected?: ((reason: any) =>
TResult | PromiseLike<TResult>) | undefined | null
): Promise<T | TResult> {
return this.promise.then(onrejected)
}
public resolve(val:T) { this._resolveSelf(val) }
public reject(reason:any) { this._rejectSelf(reason) }
[Symbol.toStringTag]: 'Promise'
}
从Typescript's Promise interface复制粘贴的then
和catch
的方法签名,并进行美化清理。如果你只是从编译器中找到了这个,那么,[Symbol.toStringTag]
行也是必需的,因为你只能从编译器中找到它。
答案 1 :(得分:1)
如何实现扩展承诺的延期承诺?
最好不要。绝对是no good reason to use deferreds。
即便如此,推迟是承诺也是一个坏主意,你应该分开这些功能:
function defer() {
var deferred = {};
deferred.promise = new Promise(resolve => {
deferred.resolve = resolve;
});
return deferred;
}
可以看出编译好的javascript很有趣。在第15行,在_this声明期间已经分配了它的属性。
是的,这就是super
的工作方式:在父构造函数调用返回并对其进行初始化之前,不能使用this
。然后在此之前调用promise执行器回调。
你必须写
export class Deferred<T> extends Promise<T> {
public resolve: T=>void;
public reject: any=>void;
constructor() {
var resolveSelf, rejectSelf
super((resolve, reject) => {
resolveSelf = resolve
_rejectSelf = reject
})
this.resolve = resolveSelf;
this.reject = rejectSelf;
}
}