【问题标题】:How can I use async/await instead of a promise (.then)如何使用 async/await 而不是 promise (.then)
【发布时间】:2019-08-17 02:46:56
【问题描述】:

我试图在我的项目中使用 async/await 而不是 .then,但它给我一个错误

这是我的代码:

export const registerUser = (userData, history) => async dispatch => {
    axios
        .post('/api/users/register', userData)
        await (res => history.push('/login'))
        .catch(err => dispatch({
                type: GET_ERRORS,
                payload: err.response.data
            })
        );
};

这是我返回的错误

未处理的拒绝(TypeError):(中间值).catch 不是函数

【问题讨论】:

  • 如果您向我们展示一些代码和错误,它将更有帮助
  • “这是一个错误”——那个错误说明了什么?

标签: es6-promise


【解决方案1】:

await 不是您替换 then() 的函数。它是一个关键字,放在解析为 Promise 的表达式之前。当您使用它时,您还可以将 catch() 方法替换为常规的 try/catch。

export const registerUser = (userData, history) => async dispatch => {
    try {
        await axios.post('/api/users/register', userData);
        history.push('/login');
    } catch (err) {
        dispatch({
            type: GET_ERRORS,
            payload: err.response.data
        })
    );
};

【讨论】:

    猜你喜欢
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    相关资源
    最近更新 更多