Jul*_*ian 4 promise typescript typescript2.1
我正在尝试取消asyncTypescript中的方法调用。
为此,我创建了一个新的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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试使用它时:
async postFileAjax<T>(file: File): CancelablePromise<T> { ... }
Run Code Online (Sandbox Code Playgroud)
我得到错误:
错误Build:Type'typeof CancelablePromise'类型在ES5 / ES3中不是有效的异步函数返回类型,因为它未引用Promise兼容的构造函数值。
如果我使用类型声明并CancelablePromise像这样返回,则它将编译:
async postFileAjax<T>(file: File): Promise<T> {
...
return CancelablePromise(...);
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?我看到您可以在ES6中将其子类化Promise(请参阅stackoverflow问题),因此我也希望在TypeScript中也可以。
使用Typescript 2.1并定位es5
起初,我对错误消息的了解并不十分清楚,但构造函数的签名应与的构造函数相同 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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
并致电:
async postFileAjax<T>(file: File): CancelablePromise <T> {
var promiseFunc = (resolve) => { resolve() };
var promise = new CancelablePromise<T>(promiseFunc);
promise.cancelMethod = () => { console.log("cancel!") };
return promise;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3080 次 |
| 最近记录: |