我在JavaScript中经常使用异步/等待。现在,我正在逐步将代码基的某些部分转换为TypeScript。
在某些情况下,我的函数接受将被调用和等待的函数。这意味着它可以返回一个承诺,只是一个同步值。我已经为此定义了Awaitable
类型。
type Awaitable<T> = T | Promise<T>;
async function increment(getNumber: () => Awaitable<number>): Promise<number> {
const num = await getNumber();
return num + 1;
}
它可以这样称呼:
// logs 43
increment(() => 42).then(result => {console.log(result)})
// logs 43
increment(() => Promise.resolve(42)).then(result => {console.log(result)})
这个很管用。但是,必须为我使用异步/等待和Awaitable
的所有项目指定TypeScript是件很烦人的事。
我真不敢相信这样的类型不是天生的,但我却找不到。TypeScript有内置型吗?
发布于 2019-05-14 11:37:48
我相信这个问题的答案是:不,没有内置的类型。
例如,在lib.es5.d.ts
和lib.es2015.promise.d.ts
中,他们将T | PromiseLike<T>
用于您的Awaitable<T>
可能具有意义的不同地方:
/**
* Represents the completion of an asynchronous operation
*/
interface Promise<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
/**
* Attaches a callback for only the rejection of the Promise.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of the callback.
*/
catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
}
在lib.es5.d.ts
中,没有什么比您的lib.es5.d.ts
更能定义PromiseLike
和Promise
了。
我认为如果他们定义了一个,他们就会在这些定义中使用它。
附带注意:基于这些定义,在您的PromiseLike
中使用Promise
而不是Promise
可能是有意义的。
type Awaitable<T> = T | PromiseLike<T>;
发布于 2019-05-07 11:34:47
async/await
总是会导致语句被包装成一个承诺,所以您的函数总是返回一个允诺。Awaitable
类型可能只是多余的.async function test() {
const foo = await 5;
console.log(foo);
const bar = await 'Hello World';
console.log(bar);
const foobar = await Promise.resolve('really async');
console.log(foobar);
}
test();
您不需要额外输入imho,因为您的函数总是有:
async function foo<T>(task: () => T | Promise<T>): Promise<T> {
const result = await task();
return result;
}
https://stackoverflow.com/questions/56021581
复制相似问题