[英]How to reject a promise in a function of both sync and async code?
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.在catch
部分抛出跟随错误将引发foo
函数用户的catch
。 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.但是第一次抛出(在if
部分)不会,为了捕捉到这个,我必须在 try/catch 中使用foo
。
How could i raise an error for the returned promise if i throw it not within a then
section?如果我不在then
部分中抛出它,我如何为返回的承诺引发错误? (Without using bluebird
and rejecting a Resolver
) (不使用bluebird
并拒绝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
.所以我发现Promise
上有一个reject
函数,它实际上完全符合我的要求,它为用作Promise
错误的函数引发错误,而不是像在try/catch
的常规throw
.
Returning this does the same a throwing an error in a Promise.then
chains返回它与在Promise.then
链中抛出错误相同
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;
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.