[英]How to make multiple API requests in a Promise in a Redux action
I'm working with React/Redux in a project and I need to make 2 separate API requests, but the second request depends on the first returning without any issues. 我正在一个项目中使用React / Redux,我需要发出2个单独的API请求,但是第二个请求取决于第一个返回而没有任何问题。 In the below example of an action, I'm trying to wrap both calls in a promise, but it's not quite working (getting a
Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.
error in the console). 在下面的操作示例中,我试图将两个调用都包装在一个Promise中,但是并不能很好地工作(出现
Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.
在控制台中出现错误)。 I don't necessarily need to do anything with the response data as a result of both calls. 由于两个调用,我不一定需要对响应数据做任何事情。 I just need them to return a 200 status or an error.
我只需要他们返回200状态或错误。
Note: Unfortunately, I can't use async/await for this example. 注意:不幸的是,在此示例中,我无法使用async / await。 Thanks!
谢谢!
export default () => {
const url = '/api';
const options = {...}
const otherOptions = {...}
return new Promise((resolve, reject) => {
return dispatch =>
// First API request
axios.post(url, options)
.then(responseA => dispatch({ type: RESPONSE_A_SUCCESS }))
.then(() =>
// Second separate API request
axios.post(url, otherOptions)
.then(responseB => {
dispatch({ type: RESPONSE_B_SUCCESS });
resolve();
})
)
.catch(error => {
dispatch({ type: errorActionType, error: error });
reject(error);
});
});
};
Your code has 2 issues: 您的代码有2个问题:
Try this instead: 尝试以下方法:
export default () => {
const url = '/api';
const options = {...}
const otherOptions = {...}
return dispatch =>
axios.post(url, options)
.then(responseA => dispatch({ type: RESPONSE_A_SUCCESS }))
.then(() => axios.post(url, otherOptions))
.then(responseB => dispatch({ type: RESPONSE_B_SUCCESS }))
.catch(error => {
dispatch({ type: errorActionType, error: error });
reject(error);
});
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.