In this lesson, you gave the planner’s request for Keiko’s holidays in Japan a deadline, watched the deadline pass before Nager.Date’s answer arrived, and then gave the server a fair deadline that it met.
Key Points
- A real server can take its time. Without a deadline, the
awaitkeeps waiting, and the planner can’t move on to its next step, sometimes for minutes. AbortSignal.timeout()gives back a signal that aborts itself after the milliseconds you pass, with aTimeoutErroras its reason. The signal only announces the stop. The work stops only if it holds the signal.fetch()can hold a signal. Its options object, the one that carried the method and body to the trip board, takes asignaltoo.- The script’s deadline of 20 milliseconds is a toy, too short on purpose. In the recorded runs, Nager.Date took about a tenth of a second to answer. A real planner would give a server a few seconds. Timings vary, so on your network you might see a status, or a
TypeErrorif the request fails. - The signal’s timer starts counting as the options object is built, and right after, the call to
fetch()starts the request with that signal. When the deadline passes before any answer arrives, the signal aborts, andfetch(), which holds the signal, drops the request, and the planner stops waiting for the answer. - An abort can’t take back a request that already reached the server. If it got there, the server may still answer, but nobody reads it. Then the promise rejects with the signal’s reason.
fetch()rejects with the reason itself, aTimeoutError, so checking for anAbortError, as the promise timer fromnode:timers/promisestaught you, would miss it. That timer rejects with anAbortErrorand keeps theTimeoutErrorin itscause. Only a plain.abort()from anAbortControllergivesfetch()anAbortError. So when the error’snameis"TimeoutError", you know a deadline passed.- With a deadline of five seconds, the answer arrived well inside it in the recorded run, and the status was
200. The promise fromfetch()fulfilled when the headers arrived, but the deadline still covers reading the body, so a deadline that passes later can still reject the.json()call that reads the body.
The rule is that when you give fetch() a signal from AbortSignal.timeout() and the deadline passes first, fetch() stops waiting for the answer, and the signal’s TimeoutError rejects its promise. The planner now has three outcomes to tell apart:
- A
Responsewhoseokisfalse: the server answered “no.” - A
TypeError:fetch()couldn’t complete the request, from a network failure or a bad URL. - A
TimeoutError: no answer in time.