我试图取消打字稿中的async
方法调用。
为此,我创建了一个新的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> { ... }
我收到错误:
错误构建:键入&#39; typeof CancelablePromise&#39;在ES5 / ES3中不是有效的异步函数返回类型,因为它不引用与Promise兼容的构造函数值。
如果我使用类型声明并返回CancelablePromise
,就像这样编译:
async postFileAjax<T>(file: File): Promise<T> {
...
return CancelablePromise(...);
}
我做错了什么?我在ES6中看到你可以继承Promise
(参见stackoverflow question),所以我也希望它也能用在TypeScript中。
使用Typescript 2.1并定位es5
答案 0 :(得分:1)
首先我没有完全清楚错误消息,但构造函数的签名应该与Promise
的构造函数相同。所以这将编译:
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;
}