【问题标题】:One promise with undefined as return type infects other promises in Promise.all with undefined一个返回类型为 undefined 的 Promise 会感染 Promise.all 中带有 undefined 的其他 Promise
【发布时间】: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


【解决方案1】:

感谢to this answer,我能够通过显式声明类型来修复它:

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

仍然很好奇这是什么原因。

【讨论】:

    猜你喜欢
    • 2020-11-28
    • 2018-04-18
    • 2014-05-12
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 2023-04-01
    • 2021-06-05
    • 2020-06-12
    相关资源
    最近更新 更多