我想制作一个带有正确错误处理的类型化异步函数。
我可以这样定义一个:
export async function doSomething(userId:string) : Promise<ISomething | void> {
let somthing: ISomething = {};
try {
something.user = await UserDocument.findById(userId);
something.pet = await PetDocument.findOne({ownerId:userId});
return Promise.resolve(something);
} catch (err){
console.log("I would do some stuff here but I also want to have the caller get the error.");
return Promise.reject(err);
}
}
...这似乎可行,但是(出于明确的原因),如果我尝试将结果分配给 ISomething
对象,我收到错误 Type 'void | ISomething' is not assignable to type 'ISomething'
.
let iSomething:ISomething;
iSomething = await doSomething('12'); //this give me the error
我明白为什么会这样。我的问题是,在这种情况下我应该使用什么模式来处理错误?请注意,如果返回类型为 Promise<IProfile>
相反,我收到 return Promise.reject(err);
的错误行(将返回 Profile<void>
)。
代替 return Promise.reject(err);
行我可以使用 throw err;
, 但有时我想使用 Promise.reject
模式(比如我想在回来之前做更多的事情)。
我感觉我遗漏了一些关于 promises/async 的东西,但我找不到遵循这种模式的类型示例。
...请注意,如果我使用完整的 Promise 模式,它会正常工作:
doSomething('12')
.then( (something) => {//do stuff})
.catch( (err) => {//handle error});
我应该只使用 throw
吗?忘记Promise.reject
?如果我使用 throw
, 将 .catch()
被适当触发?
最佳答案
首先不返回 promise 是我通常如何实现异步等待模式:
export async function doSomething(userId:string) : Promise<ISomething>{
let something: ISomething = {};
try {
something.user = await UserDocument.findById(userId);
something.pet = await PetDocument.findOne({ownerId:userId});
return something;
} catch (err){
console.log("I would do some stuff here but I also want to have the caller get the error.");
throw(err);
}
}
因此,如果您不必进行中间清理,您可以将其简化为:
export async function doSomething(userId:string) : Promise<ISomething>{
let something: ISomething = {};
something.user = await UserDocument.findById(userId);
something.pet = await PetDocument.findOne({ownerId:userId});
return something;
}
有
后续等待的函数捕获异常或
调用函数处理被拒绝的 promise
关于javascript - 在 TypeScript 中使用 Promises 的异步函数的正确错误模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41863251/