I'm practicing with asynchronous requests. In one of the exercises this code appears. What I don't understand is the .then() method . This method is passed a function per parameter that in turn receives another parameter. What does this second response parameter refer to? or where does it come from? I don't understand the flow of code execution, i.e. I understand the logic of the code and what it does, but I don't really understand how it does it.
Code
let luke
function _handleError(err) {
console.log(`Request failed: ${err}`)
}
fetch('https://www.swapi.co/api/people/1/')
.then(function a(response) {
return response.json()
})
.then(function b(json) {
luke = json
return fetch(luke.homeworld)
})
.then(function c(response) {
return response.json()
})
.then(function d(json) {
luke.homeworld = json
console.log(`${luke.name} nacio en ${luke.homeworld.name}`)
})
.catch(err => _handleError(err))
The fetch method makes a GET request to the URL it receives as a parameter and returns a promise ( Promise ) of a response ( Response ). A promise represents a value that will be available in the future (or never).
.then
When that value is available, the functions that we indicate through the ,.catch
and/or methods will be executed.finally
.What complicates the understanding is that the response object has a .json() method which, in turn, returns a promise , so I'll write the code somewhat simplified to make it easier to follow:
You can find more information in this question and its answers