gpt4 book ai didi

Typescript:Promise 的子类/扩展:不引用 Promise 兼容的构造函数值

转载 作者:搜寻专家 更新时间:2023-10-30 21:19:58 24 4
gpt4 key购买 nike

我正在尝试在 Typescript 中取消我的 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> { ... }

我得到错误:

Error Build:Type 'typeof CancelablePromise' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value.

如果我使用类型声明并返回 CancelablePromise,那么它会编译:

async postFileAjax<T>(file: File): Promise<T>  { 
...
return CancelablePromise(...);
}

我做错了什么?我看到在 ES6 中你可以将 Promise 子类化(参见 stackoverflow question ),所以我希望在 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;
}

关于Typescript:Promise 的子类/扩展:不引用 Promise 兼容的构造函数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43327229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com