I've created a unique Promise
class. How can I incorporate it with async/await
?
type Resolve<T> = (x: T | PromiseLike<T>) => void
type Reject = (reason?: any) => void
class CustomizedPromise<T> extends Promise<T> {
constructor(f: (res: Resolve<T>, rej: Reject) => void) {
super((resolve, reject) => f(
(x) => {console.log(`I resolved to ${x}!`); resolve(x)},
reject
))
}
}
function increment(x: number): CustomizedPromise<number> {
return new CustomizedPromise(resolve => resolve(x + 1))
}
I can easily await
my customized promise:
function logResult() {
const result = await increment(2)
console.log(`I received result ${result}`)
}
>> logResult()
// I resolved to 3!
// I received result 3!
However, returning my customized promise from an async
method is problematic:
async toggle(): CustomizedPromise<number> {
const result = await increment(2)
return CustomizedPromise.resolve(result * 5)
}
// ERROR: The return type of an async function or method must be the global Promise<T> type.
// Did you mean to write 'Promise<number>'?
If I suppress this error using ts-ignore
, it functions properly*:
// @ts-ignore <-- Is there a workaround for this?
async function toggle(x: number): CustomizedPromise<number> {
const result = await increment(x)
return CustomizedPromise.resolve(result * 5)
}
async function main() {
const result = await toggle(2)
console.log(`I received result ${result}!`)
}
>> main()
// I resolved to 3!
// I resolved to 15!
// I received result 15!
Check out this Typescript playground example.
(*Although, there are some occurrences of undefined
promises being spawned, they don't appear to impact the overall outcome.)
Is there a way to persuade Typescript to allow me to utilize the async
keyword on a method that returns my custom promise?