我有一些等待功能:
public async func1(): Promise<ResultType1>();
public async func2(): Promise<ResultType2>();
其中一个可以返回undefined
:
public async func3(): Promise<ResultType3|undefined>();
(为了简化代码,简化了所有代码,并删除了我所有的生产缺陷)。
当我在前两个功能上使用Promise.all
时,一切都很好:
const resultAll = await Promise.all([func1(), func2()];
// resultAll: [ResultType1, ResultType2]
但是当我将func3
包含在等待等待的数组中时,突然所有返回值都可能是undefined
:
const resultAll2 = await Promise.all([func1(), func2(), func3()]);
// resultAll: [ResultType1 | undefined, ResultType2 | undefined, ResultType3 | undefined]
但是我想获取类型[ResultType1, ResultType2, ResultType3 | undefined]
的值。
为什么会发生这种情况,如何避免呢?
答案 0 :(得分:1)
感谢to this answer,我能够通过明确声明类型来解决此问题:
const resultAllExplicit = await Promise.all<ResultType1, ResultType2, ResultTyp3 | undefined>([func1(), func2(), func3()]);
对此仍然很好奇是什么原因。