In my class I got a function that contains both sync and async code, something like:
export class SomeClass(){
constructor(){
}
foo(a: SomeDataClass): Promise<void>{
if(!a){
throw new Error('a is undefined');
}
return doSomething(a.value).then(()=>{
console.log('done');
}).catch((error)=>{
throw error;
});
}
}
export class SomeDataClass(){
public value: number;
public name: string;
constructor(){
}
}
Throwing the follow errors in the catch
part would raise the catch
for the user of foo
function. but the first throw (in the if
section) wont, in order to catch this i would have to surroun the use of foo
within a try/catch.
How could i raise an error for the returned promise if i throw it not within a then
section? (Without using bluebird
and rejecting a Resolver
)
Please let me know if something is missing.
Thanks in advance for the help.
So I have found out there is a reject
function on the Promise
which actually does exactly what i was looking for, it raises an error for the function its used in as a Promise
error and not like a regular throw
to catch within a try/catch
.
Returning this does the same a throwing an error in a Promise.then
chains
foo(a: SomeDataClass): Promise<void>{
if(!a){
return Promise.reject('a is undefined'); //<----- Promise.reject
}
return doSomething(a.value).then(()=>{
console.log('done');
}).catch((error)=>{
throw error;
});
}