简体   繁体   English

如何在catch语句之外的异步/等待中拒绝?

[英]How to reject in async/await outside of catch statement?

As outlined by this SO post and answer , it is customary to throw an error from the catch statement that resides inside an async/await function like so: 如此SO post and answer所概述的,习惯上是从位于异步/等待函数内的catch语句抛出错误,如下所示:

} catch (error) {
    throw new Error(400);
}

As highlighted by that same post, you typically wouldn't return a rejected promise (see below) since it's a semantic mis-match with 'try-catch' statements. 正如同一篇文章所强调的那样,由于它与“ try-catch”语句在语义上不匹配,因此通常不会返回被拒绝的promise(请参见下文)。

} catch (error) {
    return Promise.reject(new Error(400));
}

By that same logic, should I be returning rejected promises when returning errors outside of catch statements from my async/await function instead of throwing them? 按照同样的逻辑,当从async / await函数返回catch语句之外的错误而不是抛出错误时,我应该返回被拒绝的承诺吗?

In other words is the following semantically inconsistent with the above logic? 换句话说,以下内容在语义上与以上逻辑不一致吗?

async function promise () {
    throw new Error('Some error');
}

And, is this the preferred way of returning an error inside an async/await function since async/await functions implicitly return a promise? 并且,这是在async / await函数内部返回错误的首选方法,因为async / await函数隐式地返回了promise?

async function promise () {
    return Promise.reject(new Error(400));
}

I'm aware both of the above snippets allow errors to be caught when consuming the promise. 我知道以上两个摘要都允许在使用诺言时捕获错误。

You generally use throw where you can, ie in async function s or then callbacks, because it is simpler and therefore easier to read. 通常,在可能的地方使用throw ,即在async function then回调中使用,因为它更简单,因此更易于阅读。 return Promise.reject(…) does work but is lengthy. return Promise.reject(…)可以工作,但是很长。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM