axios get-多个api调用,从第一个api到后续调用的响应 [英] axios get - multiple api calls with response from first api to subsequent calls

查看:189
本文介绍了axios get-多个api调用,从第一个api到后续调用的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用axios进行多个api调用-当我必须将值从我的第一个api响应传递给所有后续调用时.我还有2个要在getData函数中进行的调用,我必须在其中传递y第一个api响应{data}的值-如何使用axios链接multipl请求? 2个下一个呼叫依赖于第一个呼叫-它们彼此不依赖-它们可以并行发生-我唯一的问题是-我无法将响应数据传递到后续端点.

How to make multiple api calls with axios - when I have to pass a value from my first api response to all subsequent calls. I have 2 other calls to be made inside getData function where I have to pass a value from y first api response {data} - how to chain multipl requests with axios? 2 next calls are dependent on first call - they are not dependant on each other - they can happen in parallel - the only issue I have is - I am not able to pass the response data to the subsequent end-points.

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

推荐答案

类似的方法应该适用于整个结构.

Something like this should work for an overall structure.

异步函数getData最终将返回最后两个请求的响应数组.

The async function getData will ultimately return an array of the responses from the last two requests.

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请求接收的数据,然后再将其传递给后两个数据.

Note that you may need to modify the data received from the original get request before passing it to the next two.

您可以通过将.then链接到Promise上来做到这一点...

You can do this by chaining .then onto the Promise like so...

function getDatafromService() {
  const endpoint = "api-url";
  return Request.get(endpoint).then(({data}) => modify(data));
}

这篇关于axios get-多个api调用,从第一个api到后续调用的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆