简体   繁体   English

ReactJS和Promise:那么如何调用catch?

[英]ReactJS and Promise: How to call catch inside then?

So, I have got an action creator (that returns a function - I use redux-thunk). 因此,我有一个动作创建器(返回一个函数-我使用redux-thunk)。 Inside the function the creator returns, I call a dispatch method and chain the then and catch methods. 在创建者返回的函数内部,我调用了一个dispatch方法, then链接thencatch方法。 Here how it looks like: 这里看起来像:

export function actionCreator(someData) {
    (dispath, getState) => {
        return dispatch(someAction)
        .then(resp => {
            //do something
            // GO TO CATCH
        })
        .catch(err => {
            return err;
        })
    }
}

You see the GO TO CATCH comment over there? 您在那看到GO TO CATCH评论吗? So, how can I go to the catch block from there? 那么,我怎样才能从那里去到捕获区呢?

Thank you! 谢谢!

If you want to jump from the body of a .then() to the following .catch() , the easiest way is to throw an error: 如果你想从身体跳.then()到以下.catch()最简单的方法是抛出一个错误:

throw new Error('I meant to blow up here.');

The error you throw is what will be passed to the body of the .catch() (the err variable, in your case). 您引发的错误将传递给.catch()的主体.catch()在您的情况下为err变量)。

Please note that your example already looks suspect though: your catch block is catching an error and then returning it as if the error was a regular value, which means any upstream promise-based handling will assume the dispatch was successful. 请注意,您的示例看起来已经很可疑:您的catch块正在捕获错误,然后返回 ,就好像该错误是常规值一样,这意味着任何基于上游promise的处理都将假定调度已成功。 Are you sure that's what you want? 您确定那是您想要的吗?

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

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