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