Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using a fetch inside another fetch in 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)   }); 
like image 578
Dvlpr Avatar asked Dec 05 '16 18:12

Dvlpr


People also ask

Can you fetch inside a fetch?

Yes. Your code is fine. Except that after the second request, fetch(anotherUrl). then(function(response) { , I would replace return response.

How use multiple fetch in JavaScript?

Now to do the parallel requests, we can pass all the fetch requests as an array to the Promise. all() mehtod like this, // 3 fetch requests for 3 endpints // and converting to JSON using the json() method const fetchReq1 = fetch( `https://jsonplaceholder.typicode.com/todos/1` ). then((res) => res.

How fetch data fetch in JavaScript?

JavaScript | fetch() Method The fetch() method requires one parameter, the URL to request, and returns a promise. Syntax: fetch('url') //api for the get request . then(response => response.

Is there an alternate fetch function?

We have compiled a list of solutions that reviewers voted as the best overall alternatives and competitors to Fetch, including FileZilla, Citrix ShareFile, MOVEit, and WinSCP.


1 Answers

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.

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, '\n');        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; }
like image 98
Ori Drori Avatar answered Sep 17 '22 14:09

Ori Drori