FAQ: Requests with Fetch API - Handling a GET Request

Maybe this is just a phrasing thing, but one key point of a RESTful API is that you should never have to understand how the API works, only what data it makes public and what methods are available to get and manipulate that data.

At this stage in learning, I don’t think it would be expected for anyone to know how to learn and use real API’s, I expect (hope) that will be covered in future lessons. APIs will always come with documentation, and once you learn how this works, a properly documented API is actually fairly easy to pick up and use. There are standards and tools like Swagger that make this process straightforward and consistent.

In the boilerplate given, in the first argument of the first .then(), we have a callback function with an if statement inside the code block of the callback function. then a new error underneath the if statement. The lesson says “Inside the callback function, the ok property of the response object returns a Boolean value. If there are no errors, response.ok will be true and the code will return response.json().
If response.ok is a falsy value, our code will throw an error.”

What I don’t understand is why the “throw new Error” bit is not in an else statement? To me, the way it is at the moment looks like it will run after the if statement no matter what, but surely if it should only run if there is a falsey value, there should be an if/else?

1 Like

You are referring to the code,
scrn1

You can certainly use if/else to make it explicit, but the way the code is written, it effectively is the same as an if/else even without the else keyword/block. The thing to note is the presence of the return keyword in the body of the if block. That is an important detail (You will see this pattern of omitting the else in a variety of codes as long as the logic is not affected by the omission).

Consider the following functions. func1 and func2 are equivalent even though the else keyword/block hasn’t been explicitly used in func2. But, func3 doesn’t work properly.

function func1(offer) {
    if (offer <= 0) { 
        console.log("No sale!!!");
        return;
    } else {
        console.log("SOLD!!!");
    }
}

// func2 is equivalent to func1 even without else keyword/block.
function func2(offer) {
    if (offer <= 0) { 
        console.log("No sale!!!");
        return;
    }
    console.log("SOLD!!!");
}

// Omitting else keyword/block breaks the logic.
// We need to use else keyword/block to avoid this.
function func3(offer) {
    if (offer <= 0) { 
        console.log("No sale!!!");
    }
    console.log("SOLD!!!");
}


func1(0); // "No sale!!!"
func1(23); // "SOLD!!!"

func2(0); // "No sale!!!"
func2(23); // "SOLD!!!" 

func3(0); // "No sale!!!" and "SOLD!!!" both logged
func3(23); // "SOLD!!!" 

Coming back to the code in the screenshot from the lesson. Let’s see what happens in three scenarios:

  • Scenario A: Fetch request fails
    The promise will be rejected with networkError.message logged to the console. The second then will not fire.

  • Scenario B: Fetch request succeeds and response is ok.
    The promise will succeed and the callback function will be called.
    Since the if condition is true, return response.json(); will be executed and we will exit the first then. The return keyword ensures that we don’t execute any other statement in the first callback function.
    The json response will be passed as an argument to the second then and assigned to the parameter jsonResponse. We can then do stuff with this data.

  • Scenario C: Fetch request succeeds but response is not ok.
    The promise will succeed and the callback function will be called.
    The if condition is false, so we will move on to the next statement in the callback function.
    throw new Error('Request failed!'); will be executed. An error will be thrown and execution will halt.

If you wanted, you could certainly use the else keyword and block to make things explicit.

if (response.ok) {
    return response.json();
} else {
    throw new Error('Request failed!');
}

The code in the screenshot captures the same logic without using the else block explicitly.

Hi, thanks so much for this explanation! I hadn’t realised it was possible to omit the else keyword in certain circumstances. This has been a huge help, thanks again :slight_smile:

I have been learning javascript for one month, all of the instructions that are given, I can solve them by my own and I am happy about that but every exercise has a helper function and when I am thinking of making a project and applying async wait or promise or fetching API and playing with HTTPs it feels like useless, it feels like I cannot even make a basic app. I don’t know if this problem is happening to me or other people too. if so, please tell me how to overcome this problem.

Why in this exercise we don’t use import to access the “helpeFunction.js” from main.js? We are using “renderResponse” wich is inside the helpeFunction.js. Thanks :smiley:

Have a look at the bottom of theindex.html file (click on folder directory icon in top left corner of editor), and have a look at this thread: Code using function from another file without import / export

1 Like