Saturday, April 13, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  148] [ 4]  / answers: 1 / hits: 82261  / 8 Years ago, mon, december 5, 2016, 12:00:00

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

More From » promise

 Answers
101

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




[#59808] Friday, December 2, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bryantc

Total Points: 455
Total Questions: 96
Total Answers: 110

Location: San Marino
Member since Thu, Jun 30, 2022
2 Years ago
;