Question
In this exercise, we placed an await
within the if statement inside the try
block, as follows
try {
const response = await fetch(endpoint);
if(response.ok){
const jsonResponse = await response.json(); // This line
...
}
...
}
Why do we also include an await
inside the if statement block if the response.ok
property was checked?
Answer
The reason for this is that the ok
property of the response may be received before the body of the response.
To clarify what might happen, we can walk through the code. The first await
will receive the HTTP status and headers although it may not have the body of the response yet.
After this, the if statement checks if the response is valid. If it is not valid, the code could continue. If it is valid, then the await
inside the if statement will await for the rest of the response body to be received and obtain the result of the json()
call result.