未定义为返回类型的一个诺言会感染Promise.all中其他未定义的诺言

时间:2020-02-17 11:51:45

标签: node.js typescript promise async-await

我有一些等待功能:

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]的值。

为什么会发生这种情况,如何避免呢?

1 个答案:

答案 0 :(得分:1)

感谢to this answer,我能够通过明确声明类型来解决此问题:

const resultAllExplicit = await Promise.all<ResultType1, ResultType2, ResultTyp3 | undefined>([func1(), func2(), func3()]);

对此仍然很好奇是什么原因。

相关问题