如何在 Redux 操作中的 Promise 中发出多个 API 请求
How to make multiple API requests in a Promise in a Redux action
我在一个项目中与 React/Redux 合作,我需要提出 2 个单独的 API 请求,但第二个请求依赖于第一个 returning,没有任何问题。在下面的操作示例中,我试图将两个调用包装在一个承诺中,但它不太有效(在控制台中出现 Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.
错误)。由于两次调用,我不一定需要对响应数据执行任何操作。我只需要它们 return 200 状态或错误。
注意: 不幸的是,我不能在这个例子中使用 async/await。谢谢!
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);
});
});
};
您的代码有 2 个问题:
- 它 returns 一个承诺,而不是 "plain object"。
- 您正在嵌套承诺而不是按顺序附加它们
试试这个:
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);
});
});
};
我在一个项目中与 React/Redux 合作,我需要提出 2 个单独的 API 请求,但第二个请求依赖于第一个 returning,没有任何问题。在下面的操作示例中,我试图将两个调用包装在一个承诺中,但它不太有效(在控制台中出现 Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.
错误)。由于两次调用,我不一定需要对响应数据执行任何操作。我只需要它们 return 200 状态或错误。
注意: 不幸的是,我不能在这个例子中使用 async/await。谢谢!
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);
});
});
};
您的代码有 2 个问题:
- 它 returns 一个承诺,而不是 "plain object"。
- 您正在嵌套承诺而不是按顺序附加它们
试试这个:
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);
});
});
};