【发布时间】:2020-06-01 08:22:46
【问题描述】:
我有几个等待函数:
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] 类型的值。
为什么会发生,我该如何避免?
【问题讨论】:
-
如果有人可以为这个问题建议一个信息更丰富的标题,那将是非常受欢迎的。
标签: node.js typescript promise async-await