In this lesson, you watched Portugal’s holidays arrive from Nager.Date on a timeline, then timed the two steps of the same request in a real run.
Key Points
- The call to
fetch()hands back a promise right away, still pending. Then Node sends theGETrequest, and the firstawaitwaits on that promise. - The response comes back the way curl printed it, top first. The status line and headers arrive first, and that’s all
fetch()waits for. Its promise fulfills with aResponsewhose status,okflag and headers are already in it, so the log lines after the firstawaitcan run. - The body may still be on its way behind them. On a fast connection, some of it may already be here, but the
Responsehasn’t read any of it yet. Callingresponse.json()gives you a second promise. It reads the body to its end, whether it has already arrived or is still arriving, then parses it as JSON. Only then does it fulfill, with Portugal’s 17 holidays. - When you timed the two steps with
Date.now(), the status200was logged after about a tenth of a second, and the body was read a few milliseconds later. These times show when your code resumes after eachawait, not when the bytes arrive. Your times will differ on every run, but the order stays the same. How long the second step takes depends on the body’s size and the connection. - For
XX, the made-up country code that got a404back when you sorted status codes, the status404is logged after the firstawaittoo. Its status line arrives first, and its body, the JSON that describes the problem, follows behind. So from the status alone, the planner can tell whether the body is holidays or a description of a problem, before it reads any of it.
The rule is that the promise from fetch() fulfills as soon as the status line and headers arrive. The body may still be on its way, and response.json() waits for all of it.