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

查看:82
本文介绍了在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返回一个承诺,你可以链接多个承诺,并使用结果第二个请求中的第一个请求:

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

该示例使用 SpaceX API 获取最新发射的信息,找到火箭的id,并获取火箭的信息。

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

var url = 'https://api.spacexdata.com/v2/launches/latest';

var result = fetch(url, {
    method: 'get',
  }).then(function(response) {
    return response.json(); // pass the data as promise to next then block
  }).then(function(data) {
    var rocketId = data.rocket.rocket_id;

    console.log(rocketId, '\n');
  
    return fetch('https://api.spacexdata.com/v2/rockets/' + rocketId); // make a 2nd request and return a promise
  })
  .then(function(response) {
    return response.json();
  })
  .catch(function(error) {
    console.log('Request failed', error)
  })

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

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

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

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