Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

    Then the response body is parsed to JSON
The "res => res.json()" call? But what does this do? res seems to be used nowhere and just discarded without any side effects.


If it's a simple statement of this form, the result of the expression is returned.

so res => res.json() is just like having a callback like:

function(res) { return res.json() }

and the next part in the then() chain, takes that result as "planet".

Basically, that last part of the chain, has a signature like:

(function callback(...), function errorCallback(...))

and the callback part gets the result of the previous step as "planet" (if all went ok). If there was an error in the previous steps of the chain, the errorCallback would get called, with the exception passed in as "error".


If it makes it easier to reason about, it's equivalent to:

    // The Promise resolves when the server starts responding
    const response = await fetch(…);
    
    // The Promise resolves when both the transfer and the JSON parsing ended
    const body = await response.json();
So, yes, `response` is only used once and then discarded.

`fetch()` may fool you into thinking that it resolves when the request is complete, but it's always a 2-step operation (unless you start implementing a streaming interface, then it's more than 2 steps)


Ah! The equivalent with await seems much clearer to me.


This is a shorthand for

    function (r) { return r.json()}
Note the extra return. We return the JSON decoded response that is our planet. and use its value to set state if no error occured


Got it! Thanks!


This is pretty straightforward es6. The difference between =>{} and just => is confusing at first. One is a function body and the other is an implied return statement.


`res.json()` is the return value of the first `then` block, which is then passed to the second `then` block as `planet` (if json parsing doesn't throw an error).


res => res.json() returns the result of res.json()

That function is thenable so following it .then is called and the result or error is passed to the first or second function respectively.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: