如何将这个promise返回的函数更改为异步等待



最初,我使用基于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;
});
};
};

正如您在上面的代码中看到的,函数是返回promise。但当我试图将其更改为异步等待时

我的模拟器是给我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');
}
};
};

您的async应用于错误的函数,它应该在调度函数上

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');
}
};
);

NB:我把牙套拆了;箭头函数返回是隐含的https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

最新更新