0

I stumbled upon the following code (reference):

function handleErrors(response) {
    if (!response.ok) {
        throw Error(response.statusText);
    }
    return response;
}
fetch("http://httpstat.us/500")
    .then(handleErrors)
    .then(response => console.log("ok") )
    .catch(error => console.log(error) );

I would have expected something like this:

then((response) => { handleErrors(response) })

How is it possible that response is successfully being passed to the reference of handleErrors()? Does it have something to do with promises or is this a javascript pattern that I don't know about?

Fusscreme
  • 152
  • 9
  • why? `handleErrors` is a function ... also, your alternative would result in undefined response in `then(response` – Bravo Jul 09 '21 at 06:32
  • 1
    `.then(handleErrors)` - this is same as: `.then(function handleErrors(response) { ... })`. `then()` method takes callback functions as arguments; you can either pass those callbacks as `.then((res) => { ... })` or define the function somewhere else and just pass its name: `.then(handleErrors)` – Yousaf Jul 09 '21 at 06:41
  • @Yousaf Okay, I see. But: It might as well be `function handleErrors(a) { ... }`. How does `handleErrors` know that `a` is the response? Is it always the case that the value of Promise.resolve is being passed to the reference as the first argument? – Fusscreme Jul 09 '21 at 07:05
  • 1
    When you pass some callback function as an argument to another function, you need to see what argument will the caller pass to your callback function. In the case of `then()`, it will pass the value, to the first callback function, with which the promise, on which it is called, resolves with. – Yousaf Jul 09 '21 at 07:08
  • I get it! So it is nothing special at all. General pattern: `function caller(callback) { let foo = 'foo'; callback(foo); }; function callbackFunction(bar) { console.log(bar); }; caller(callbackFunction);` Thank you. – Fusscreme Jul 09 '21 at 07:19
  • 1
    Does this help? [Confusion with how thenable callback works in Promise?](https://stackoverflow.com/q/59878462) – VLAZ Jul 09 '21 at 10:03
  • It does! Perfect :) Thank you. – Fusscreme Jul 09 '21 at 18:56

0 Answers0