Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise, fetch, codestyle. Please, explain .then(checkStatus).then(parseJSON)

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.

like image 216
Oksana Avatar asked Feb 21 '26 00:02

Oksana


1 Answers

.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)

like image 140
Jaromanda X Avatar answered Feb 23 '26 12:02

Jaromanda X