Wil*_*lyC 5 javascript node.js promise async-await typescript
我想使用正确的错误处理来创建一个类型化的异步函数.
我可以这样定义一个:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
...这似乎有效,但(由于明确的原因),如果我尝试将结果分配给ISomething对象,我会得到错误Type 'void | ISomething' is not assignable to type 'ISomething'.
let iSomething:ISomething;
iSomething = await doSomething('12'); //this give me the error
Run Code Online (Sandbox Code Playgroud)
我知道那是为什么.我的问题是,在这样的情况下,我应该使用什么模式进行错误处理?请注意,如果返回类型是,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});
Run Code Online (Sandbox Code Playgroud)
我应该只是在使用throw而忘记Promise.reject?如果我使用throw,是否会.catch()被恰当地触发?
首先不返回承诺是我通常实现异步等待模式的方式:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
因此,如果您不必进行中间清理,您可以将其精简为:
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;
}
Run Code Online (Sandbox Code Playgroud)
并有
随后等待的函数捕获异常或
调用函数处理被拒绝的承诺
| 归档时间: |
|
| 查看次数: |
973 次 |
| 最近记录: |