在一个函数中发出两个获取请求,并且之间存在延迟 [英] making two fetch requests in one function with a delay in between

查看:64
本文介绍了在一个函数中发出两个获取请求,并且之间存在延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有2个端点,我向第一个端点发出发布"请求,并且在响应中,我应该获得在第二个请求端点URL中使用的某种ID.所以我想延迟一会儿,直到我收到第一个请求的响应.

so I have 2 endpoints, I'm making a "post" request to the first one and in the response I should get some kind of id that I use in the second request endpoint url. so I want to make a delay or something till I get the response from the first request.

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 => {

    })
}

推荐答案

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

There is no need for a delay per se. You can place your second request in the .then of the first request. This will ensure that your second request will run only once the first one has resolved. Another important note here, is that if you need a value of the first response in order to make the second request, you can only do that in the .then of the first request because otherwise the value you need to make the second request will be out of scope. Here is your code with the required modification.

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 => {

        })
    })
}

这篇关于在一个函数中发出两个获取请求,并且之间存在延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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