在一个函数中发出两个获取请求,之间存在延迟

时间:2018-10-11 22:21:38

标签: javascript reactjs fetch-api

所以我有2个端点,我向第一个端点发出“发布”请求,并且在响应中,我应该获得在第二个请求端点url中使用的某种ID。所以我想延迟一下,直到我收到第一个请求的响应。

req = () => {
  fetch('url', {
      method: 'POST',
      headers: {
        'Authorization': bearer,
        'Content-Type': 'application/json',
      },
      body: 
    })
    .then(response => response.json())
    .then(json => {

    })
  fetch(`url with the id I get from the first request`, {
      method: 'GET',
      headers: {
        'Authorization': bearer,
        'Content-Type': 'application/json',
      }
    })
    .then(response => response.json())
    .then(json => {

    })
}

2 个答案:

答案 0 :(得分:0)

本身无需延迟。您可以将第二个请求放在第一个请求的.then中。这将确保您的第二个请求仅在第一个请求解决后才运行。这里的另一个重要说明是,如果您需要第一个响应的值才能发出第二个请求,则只能在第一个请求的.then中执行此操作,因为否则,您需要执行第二个请求的值请求将超出范围。这是带有所需修改的代码。

req = () => {
  fetch('url', {
    method: 'POST',
    headers: {
      'Authorization': bearer,
      'Content-Type': 'application/json',
    },
    body: 
    })
    .then(response => response.json())
    .then(json => {
      fetch(`url with json.id or whatever`, {
        method: 'GET',
        headers: {
          'Authorization': bearer,
          'Content-Type': 'application/json',
        }
      })
        .then(response => response.json())
        .then(json => {

        })
    })
}

答案 1 :(得分:-1)

您可以将第一个请求中的第二个提取请求链接为:

req = () => {
  fetch("url", {
    method: "POST",
    headers: {
      Authorization: bearer,
      "Content-Type": "application/json"
    }
    body:
  })
    .then(response => response.json())
    .then(json => {
      fetch("url with the id I get from the first request", {
        method: "GET",
        headers: {
          Authorization: bearer,
          "Content-Type": "application/json"
        }
      })
        .then(response => response.json())
        .then(json => {});
    });
};

或者您可以使用async/await

req = async () => {
    const first = await ( await fetch( "url", {
      method: "POST",
      headers: {
        Authorization: bearer,
        "Content-Type": "application/json",
      },
      body:
    } ) ).json();

    const second = await ( await fetch( `http://some.url${ first.id }` ),
    {
      method: "GET",
      headers: {
        Authorization: bearer,
        "Content-Type": "application/json",
      },
    } ).json();

    // use the variable second as your last result here.
  };