我有一些等待函数:
public async func1(): Promise<ResultType1>();
public async func2(): Promise<ResultType2>();
其中一个可以返回未定义
:
public async func3(): Promise<ResultType3|undefined>();
(为了便于阅读,所有代码均已简化,所有生产缺陷均已删除)。
当我在前两个函数上使用 Promise.all
时,一切都很好:
const resultAll = await Promise.all([func1(), func2()];
// resultAll: [ResultType1, ResultType2]
但是当我将 func3
包含在要等待的 promise 数组中时,突然所有返回值都可能未定义
:
const resultAll2 = await Promise.all([func1(), func2(), func3()]);
// resultAll: [ResultType1 | undefined, ResultType2 | undefined, ResultType3 | undefined]
但是我想获取类型的值[ResultType1, ResultType2, ResultType3 |未定义]
。
为什么会发生这种情况,如何避免?
谢谢to this answer ,我可以通过显式声明类型来修复它:
const resultAllExplicit = await Promise.all<ResultType1, ResultType2, ResultTyp3 | undefined>([func1(), func2(), func3()]);
还是很好奇这是什么原因。
我是一名优秀的程序员,十分优秀!