如何将此承诺返回的函数更改为异步等待?

时间:2021-05-12 16:38:04

标签: reactjs react-native asynchronous redux async-await

最初我使用基于 Promise 的脚本编写代码 .then().catch

但是当我尝试将其更改为 async await 函数时。它不再工作了。 请有人帮我解决这个问题。

我的旧代码有效

export const fetchToken = (params) => {
    return (dispatch) => {
        const config = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        };
        return axios
            .post(`/api/token`, params, config)
            .then((res) => {
                tokenData = res.data.access_token;
                dispatch({
                    type: LOGGED_IN,
                    payload: res.data,
                });
            })
            .catch((err) => {
                console.log(err);
                alert('Provided username and password is incorrect');
                throw err;
            });
    };
};

正如您在上面的代码中看到的,该函数是返回一个承诺。但是当我尝试将其更改为 async await

我的模拟器给了我 Unexpected reserved work await 错误

这是我在 redux 中的 async await 代码

export const fetchToken = async (params) => {
  return (dispatch) => {
        const config = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        };
    try {
      const response = await axios.post(`/api/token`, params, config);
            const data = await response.json();
            tokenData = data.access_token
            dispatch({ type: LOGGED_IN, payload: res.data})
    } catch {
                console.log(err);
        alert('Provided username and password is incorrect');
        }
  };
};

1 个答案:

答案 0 :(得分:2)

你的 async 应用到了错误的函数上,应该是在 dispatch 函数上

export const fetchToken = (params) => (
  async (dispatch) => {
        const config = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        };
    try {
      const response = await axios.post(`/api/token`, params, config);
            const data = await response.json();
            tokenData = data.access_token
            dispatch({ type: LOGGED_IN, payload: res.data})
    } catch {
                console.log(err);
        alert('Provided username and password is incorrect');
        }
  };
);

注意:我已经移除了大括号;箭头函数返回是隐含的https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

相关问题