我正在尝试取消我的async
Typescript 中的方法调用。
为此,我创建了一个新的 Promise 类型,它继承自Promise
:
class CancelablePromise<T> extends Promise<T>{
private cancelMethod: () => void;
constructor(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void, cancelMethod: () => void) {
super(executor);
this.cancelMethod = cancelMethod;
}
//cancel the operation
public cancel() {
if (this.cancelMethod) {
this.cancelMethod();
}
}
}
但是当我尝试使用它时:
async postFileAjax<T>(file: File): CancelablePromise<T> { ... }
我收到错误:
错误 Build:Type 'typeof CancelablePromise' 不是 ES5/ES3 中的有效异步函数返回类型,因为它不引用 Promise 兼容的构造函数值。
如果我使用类型声明并返回CancelablePromise
,像这样然后编译:
async postFileAjax<T>(file: File): Promise<T> {
...
return CancelablePromise(...);
}
我究竟做错了什么?我发现在 ES6 中你可以子类化Promise
(see 堆栈溢出问题),所以我希望它也能在 TypeScript 中出现。
使用 Typescript 2.1 并针对 es5
错误消息一开始对我来说并不完全清楚,但是构造函数的签名应该是完全一样作为构造函数Promise
.
我已经删除了cancelMethod
来自构造函数并稍后设置它。这有效:
class CancelablePromise<T> extends Promise<T>{
public cancelMethod: () => void;
constructor(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) {
super(executor);
}
//cancel the operation
public cancel() {
if (this.cancelMethod) {
this.cancelMethod();
}
}
}
并致电:
async postFileAjax<T>(file: File): CancelablePromise <T> {
var promiseFunc = (resolve) => { resolve() };
var promise = new CancelablePromise<T>(promiseFunc);
promise.cancelMethod = () => { console.log("cancel!") };
return promise;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)