【发布时间】:2019-08-11 20:26:23
【问题描述】:
我在 React 中有一个 dataService 函数来获取我的 API。我尝试转换为 async/await 块,但似乎遇到了障碍。
使用承诺:
const dataService = (url, options, dataToPost) => {
return (dispatch, getState) => {
const { requestAction, successAction, failureAction } = options.actions;
if (options.shouldRequest(getState())) {
dispatch(requestAction());
const promise = axios.get(url, { withCredentials: true });
return promise
.then(response => {
if (response.status === 200) {
return dispatch(successAction(response, dispatch));
}
return Promise.reject(response);
})
.catch(error => {
if (error.response.status === 302) {
window.location = '/view';
}
dispatch(openErrorDialog());
return dispatch(failureAction(error));
});
}
return Promise.reject(new Error('FETCHING'));
};
};
使用异步/等待:
const dataService = async (url, options, dataToPost) => {
return async (dispatch, getState) => {
let url;
const {requestAction, successAction, failureAction} = options.actions;
if (options.shouldRequest(getState())) {
dispatch(requestAction());
const promise = axios.get(url, {withCredentials: true});
try {
const response = await promise;
if (response.status === 200) {
return dispatch(successAction(response, dispatch));
}
return Promise.reject(response);
} catch (error) {
return dispatch(failureAction(error));
}
}
return Promise.reject(new Error('FETCHING'));
};
};
错误是“操作必须是普通对象。使用自定义中间件进行异步操作。”。承诺代码完美运行。我已经在使用thunk了。请指教。
【问题讨论】:
-
你所做的一切毫无意义,因为
const promise = dataToPost ? ....不会是一个承诺 - 让我们面对现实吧,你所做的只是将dataService标记为异步,所以现在它不返回其中声明的函数,它返回该函数的承诺 -
尝试将 async 关键字从 dataService 中删除到
dataService = (url, options, dataToPost)这可能会有所帮助:stackoverflow.com/questions/50059724/…
标签: javascript promise async-await