After watching the video, and reading in [Promise.then][1] i still don't understand how it works. So i wrote an example, and printed to console but still with the output i can't understand how does it work. I hope my question are clear enough, if not please tell me and i will try to elaborate them according to your responses. This is my code:
const getCountryData = function (country) {
fetch(`https://restcountries.eu/rest/v2/name/${country}`)
.then(response => {
console.log('111111111111111');
if (!response.ok)
throw new Error(`Country not found (${response.status})`);
return response.json();
})
.then(data => {
console.log('22222222222');
const neighbour = data[0].borders[0];
if (!neighbour) return;
return fetch(`https://restcountries.eu/rest/v2/alpha/${neighbour}`);
})
.then(response => {
console.log('333333333')
if (!response.ok)
throw new Error(`Country not found (${response.status})`);
return response.json();
})
.then(data => console.log('44444444444'))
.catch(err => {
console.error(`${err} `);
})
.finally(() => {
console.log('finalyyyy')
});
console.log("after all async calls");
};
I can't understand the following things:
- If we look for example on the first then, it gets a callback as a parameter, the callback returns a Promise object. Which object calls the second then? The one that was returned from the first call to when or the one that have been returned from the callback?
- I understand that the callback is "attached" to the fetch function. e.g when the fetch function will be finished, the callback will be executed. But i can't understand how and when the second, third and fourth then are called. The first callback contains also an async function ** response.json()**, so how and when exactly the second when will be started if he need the json.response from the first when?
- If an exception occur at the first or second, how exactly the code knows to jump to catch function?
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then