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

IT技术 javascript reactjs fetch-api
2021-05-10 16:54:46

所以我有 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个回答

本身不需要延迟。您可以将第二个请求放在.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 => {

        })
    })
}

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

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