JS 12. Requests - .then() arrow function syntax?


#1

Apologies if this is a stupid question, but I couldn’t find the answer online through usual means, and I’m completely drawing a blank. So far with functions I’ve only ever seen arguments passed in the beginning (such as “const func = (arg1, arg2) => {…}”).

Then on exercise 3/17 of the Requests II lesson, I was told to type in the following:

fetch(‘https://api-to-call.com/endpoint’).then(response => {
if (response.ok) {
return response.json();
}
throw new Error(‘Request failed!’);
}, networkError => {
console.log(networkError.message);
});

The instruction states:

Add a second argument to .then() , it will be an arrow function that will handle our failures. Separate the first callback function from the second with a comma. The second callback function takes a single parameter, networkError .

In the code block of the second callback function, log networkError.message to the console.

If we could not reach the endpoint at all, e.g., the server is down, then we would get this networkError .

I thought maybe this was a way to separate the code blocks and only execute each block with its corresponding argument or something (though why would you not just use two separate functions for that?), so I tried a simple test on codepen:

const test = arg1 => {
console.log(arg1 + 1);
}, arg2 => {
console.log(arg2 + 2);
};

Which only ever seems to return undefined on the second argument if I pass it two.

I can’t think of how else to find out what’s going on here. Are these separate arguments for calling different instances of the .then() method or something? But if that were the case I don’t see how it could distinguish which argument to assign the incoming value to and which block to run. Anyway, I think I’m rambling.

Can someone please explain what this “comma + new argument + new arrow function after the first block is closed” syntax is all about, or point me to the right direction please?

Thanks in advance.


#2

Well turns out I was looking at it completely backwards, and searching the wrong resources for an answer as a result. It appears to not be a matter of arrow function syntax, but merely the .then() method taking two arguments - one for fulfilled and one for rejected: see MDN.

Anyone with the appropriate privileges who chances upon my ill-thought-out thread here, feel free to delete it.

Otherwise, here’s a good chuckle for everyone else :slight_smile: