I have test code!
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText));
}
}
function parseJSON(response) {
return response.json()
}
I can write like here:
function load(id) {
return fetch('/api/test/'+ id + '/', {method: 'get'})
.then(response => checkStatus(response))
.then(response => parseJSON(response))
.catch(error=>console.error(error))
or I can write like there:
function load(id) {
return fetch('/api/test/'+ id + '/', {method: 'get'})
.then(checkStatus)
.then(parseJSON)
.catch(error=>console.error(error))
Please explain second variant. How does it .then(checkStatus)
.then(parseJSON) work?
I just write the reference to the functions, and not run it.
.then takes functions as its arguments ... it calls the function passing in a single argument that is the resolved value of the promise
so think of
return fetch('/api/test/'+ id + '/', {method: 'get'})
.then(checkStatus)
as
return fetch('/api/test/'+ id + '/', {method: 'get'})
.then(function(resultOfPromise) {
return checkStatus(resultPromise);
})
By the way, this isn't limited to promise/then type code ... consider the following
function doThings(p1) {
console.log(p1);
return 'good bye';
}
setTimeout(doThings, 1000, "hello world");
same concept - except that the the value returned by the callback in setTimout is ignored. In
.then()however, the value returned by the callback is used as the resolved value of a Promise ... which is basically how promise chaining works (this is an over simplified explanation)
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