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) });
Yes. Your code is fine. Except that after the second request, fetch(anotherUrl). then(function(response) { , I would replace return response.
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.
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With