我想创建一个QueryPromise,它只是带有cancel方法的具体 promise 。使用方法如下:
function runQuery(text: string): QueryPromise {
return new QueryPromise((resolve,reject) => {nativeQuery(resolve)})
}
这是我的第一次尝试,希望可以理解:
interface CancellablePromise<T> extends Promise<T> {
cancel: () => void
}
// create the promise my app will use
type QueryPromise = CancellablePromise<string|boolean>
但这还不够。
经过数小时的尝试和错误,我设法接近了,但这似乎很乏味,而且除了DRY之外,什么都没有。
interface CancellablePromise<T> extends Promise<T> {
cancel: () => void
}
// also need this interface so the variable can be declared
// plus need to redeclare methods to return the new type
interface CancellablePromiseConstructor extends PromiseConstructor {
new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): CancellablePromise<T>;
cancel: () => void
}
type QueryPromise = CancellablePromise<string|boolean> // for parameter types
var QueryPromise: CancellablePromiseConstructor = Promise // for the new operator
// some example code to exercise the promise
function runQuery(text: string): QueryPromise {
return new QueryPromise((resolve,reject) => {nativeQuery(resolve)})
}
我觉得我走了很长的路要走……有人知道有更好的方法吗?
最佳答案
TypeScript接口(interface)和类型描述契约(Contract)。您的情况很好:
interface CancellablePromise<T> extends Promise<T> {
cancel: () => void
}
type QueryPromise = CancellablePromise<string | boolean>
然后,您可以根据需要实现契约(Contract)。这是一个例子:
function runQuery(text: string): QueryPromise {
let rejectCb: (err: Error) => void
let p: Partial<QueryPromise> = new Promise<string | boolean>((resolve, reject) => {
rejectCb = reject
/* ... Here the implementation of the query ... */
});
p.cancel = () => {
/* ... Here the implementation of the aborting ... */
rejectCb(new Error("Canceled"))
}
return p as QueryPromise
}
注意事项:
cancel
的实现应该拒绝 promise 。 Partial<QueryPromise>
以便以后添加成员cancel
。 关于typescript - 可以在Typescript中向Promise添加cancel方法吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46461801/