gpt4 book ai didi

node.js - 返回类型为 undefined 的一个 Promise 会感染 Promise.all 中的其他 Promise 并带有 undefined

转载 作者:太空宇宙 更新时间:2023-11-03 23:48:12 24 4
gpt4 key购买 nike

我有一些等待函数:

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()]);

还是很好奇这是什么原因。

关于node.js - 返回类型为 undefined 的一个 Promise 会感染 Promise.all 中的其他 Promise 并带有 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60261835/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com