【发布时间】:2021-07-17 01:42:53
【问题描述】:
我有一个功能。返回类型是用户的承诺:
async function doThing(): Promise<User> {
const one = await getOne();
const two = await getTwo();
return {
one,
two
}
}
我正在更改函数以使用 Promise.all:
async function doThing(): Promise<User> {
const onePromise = getOne();
const twoPromise = getTwo();
await Promise.all([onePromise, twoPromise])
.then(([one, two])=>{
return {
one,
two
}
});
}
但是现在我收到一个 TypeScript 错误:
TS2355:声明类型既不是“void”也不是“any”的函数必须返回一个值。
我很惊讶我在第二版但不是第一版的代码中遇到错误。我尝试捕捉错误,但没有任何区别:
await Promise.all([onePromise, twoPromise])
.then(([one, two])=>{
return {
one,
two
}
}).catch(error => {
return Error(error);
});
但是在Promise.all 之后抛出错误确实会使错误消失:
await Promise.all([onePromise, twoPromise])
.then(([one, two])=>{
return {
one,
two
}
});
throw new Error("oh no!")
【问题讨论】:
-
你不需要return承诺吗?
return Promise.all...? -
也许这只是一个错字或什么?我们应该这样关闭它吗?