I want to make a typed asynchronous function with proper error handling.
I can define one like this:
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);
}
}
... which works, but (for obvious reasons), if I try to assign a result to an object ISomething, I get an error message Type 'void | ISomething' is not assignable to type 'ISomething'.
let iSomething:ISomething;
iSomething = await doSomething('12');
I understand why this is so. My question is: which template should I use for error handling in this case? Note that if the return type is Promise<IProfile>instead, I get an error for the string return Promise.reject(err);(which will return 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() ?