【问题标题】:react redux Promise function to async/await将 redux Promise 函数反应到异步/等待
【发布时间】:2019-06-20 15:37:41
【问题描述】:

我有以下 redux 函数将新用户添加到我的数据库。它工作正常,但如果我在我的then 中引入另一个电话,可能需要对所有内容进行广泛的捕获。 如果我们把它变成asynctry/Catch 来处理我们所有的错误怎么办? 我尝试了一个样本,但一直缺少一些东西。 有人可以帮我安排一下吗。谢谢。

export function newUser(values) {
return function(dispatch) {
    const promise = axios.post(URL)

    dispatch(createAdminUsersRequest(promise));

    promise.then(
        user => {
            dispatch(createUsersSuccess(user));
            dispatch(fetchUsers());
            dispatch(switchUserActions(false, false, false));
        },
        function(error) {
            if (error && error.response && error.response.data)
                error = error.response.data;
            if (error && error.data) {
                error = error.data;
            }
            dispatch(createUsersFail(errors(error)));
            setTimeout(() => dispatch(createUsersFail(null)), 6000);
        }
    );

    return promise;
};

}

【问题讨论】:

    标签: reactjs redux promise async-await es6-promise


    【解决方案1】:

    promise 到 async-await 的转换非常简单。首先,通过向其添加 async 关键字将函数声明为 async。其次,你在承诺上使用await

    export function newUser(values) {
    
        return async function(dispatch) {
    
            dispatch(createAdminUsersRequest(promise));
            try {
                const user = await axios.post(URL);
                dispatch(createUsersSuccess(user));
                dispatch(fetchUsers());
                dispatch(switchUserActions(false, false, false));
            } catch(error) {
                if (error && error.response && error.response.data)
                     error = error.response.data;
                if (error && error.data) {
                     error = error.data;
                }
                dispatch(createUsersFail(errors(error)));
                setTimeout(() => dispatch(createUsersFail(null)), 6000);
            }
        };
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-24
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      • 2017-10-24
      相关资源
      最近更新 更多