如何使用axios进行多个api调用 - 当我必须将第一个api响应中的值传递给所有后续调用时。我在getData
函数中有另外两个调用,我必须从y first api response {data}
传递一个值 - 如何用axios链接multipl请求? 2下一次调用取决于第一次调用 - 它们不是相互依赖的 - 它们可以并行发生 - 我唯一的问题是 - 我无法将响应数据传递给后续的端点。
import Request from 'axios';
export function getData() {
return async function getData(dispatch) {
const { data } = await getDatafromService();
dispatch({ type: 'Data_fetch', payload: data });
};
}
async function getDatafromService() {
const endpoint = "api-url";
return Request.get(endpoint);
}
答案 0 :(得分:0)
这样的事情应该适用于整体结构。
异步函数getData最终会返回最后两个请求的响应数组。
import Request from 'axios';
export function getData() {
return async function getData(dispatch) {
const { data } = await getDatafromService();
return Promise.all([
sendDataToFirstService(data),
sendDataToSecondService(data),
])
};
}
function getDatafromService() {
const endpoint = "api-url";
return Request.get(endpoint);
}
function sendDataToFirstService(data) {
const endpont = "first-url";
return Request.post(endpoint, data)
}
function sendDataToSecondService(data) {
const endpont = "second-url";
return Request.post(endpoint, data)
}
请注意,您可能需要修改从原始get
请求中收到的数据,然后再将其传递给下一个请求。
你可以通过将.then
链接到Promise上来实现这一点......
function getDatafromService() {
const endpoint = "api-url";
return Request.get(endpoint).then(({data}) => modify(data));
}