在 javascript 中的另一个 fetch 中使用 fetch [英] using a fetch inside another fetch in javascript

查看:20
本文介绍了在 javascript 中的另一个 fetch 中使用 fetch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得一个 api,然后再调用另一个.在javascript中使用这样的代码是否明智?

I want to get an api and after that call another one. Is it wisely using a code like this in javascript?

fetch(url, {
 method: 'get',
 }).then(function(response) {  
  response.json().then(function(data) {  
    fetch(anotherUrl).then(function(response) {
      return response.json();
    }).catch(function() {
      console.log("Booo");
    });
  });  
}) 
.catch(function(error) {  
  console.log('Request failed', error)  
});

推荐答案

Fetch 返回一个 promise,你可以链接多个promise,并在第二个请求中使用第一个请求的结果,依此类推.

Fetch returns a promise, and you can chain multiple promises, and use the result of the 1st request in the 2nd request, and so on.

本示例使用 SpaceX API 获取最新发布的信息,找到火箭的id,并获取火箭的信息.

This example uses the SpaceX API to get the info of the latest launch, find the rocket's id, and fetch the rocket's info.

const url = 'https://api.spacexdata.com/v4';

const result = fetch(`${url}/launches/latest`, { method: 'get' })
  .then(response => response.json()) // pass the data as promise to next then block
  .then(data => {
    const rocketId = data.rocket;

    console.log(rocketId, '
');
  
    return fetch(`${url}/rockets/${rocketId}`); // make a 2nd request and return a promise
  })
  .then(response => response.json())
  .catch(err => {
    console.error('Request failed', err)
  })

// I'm using the result const to show that you can continue to extend the chain from the returned promise
result.then(r => {
  console.log(r.first_stage); // 2nd request result first_stage property
});

.as-console-wrapper { max-height: 100% !important; top: 0; }

这篇关于在 javascript 中的另一个 fetch 中使用 fetch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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