In this lesson, you sent two tickets to the repair café’s API at the same moment and watched the store from the previous lesson lose one of them.
Key Points
- The store reads, changes and writes. To create a ticket,
create()readstickets.json, adds the ticket to the list, and writes the whole list back. - Two tickets can arrive together. On a busy Saturday, Hana brings a kettle and Omar brings a fan, and two volunteers log them at the same moment. JavaScript runs on one thread, one line at a time, so you might expect that to be fine.
- A short script sends both at once. Its
post()function sends one ticket withfetch(), as aPOSTwith a JSON body. The twopost()calls start both requests without waiting for each other, andPromise.all()waits for both answers. - Both answers are
201 Created, and one ticket is gone. Each request was told its ticket was saved, but the list holds six tickets, not seven, andtickets.jsonagrees: Omar’s fan is there, and Hana’s kettle isn’t. - The result depends on timing, which makes it a race. Most runs lose one ticket, and which one can change. Now and then, both tickets survive, or the file ends up broken.
- The requests take turns at their awaits. When a function reaches an
await, it pauses there, and the event loop runs something else that’s ready. Hana’s request pauses at its read, and Omar’s request starts and pauses at the same read, so both reads are under way. - Both reads find five tickets. Hana’s read comes back with five tickets, and her request adds the kettle and starts writing six. Omar’s read had got the file before Hana’s write changed it, so his copy holds five tickets too, and his request adds the fan and writes six.
- Omar’s six replace Hana’s six. In the run shown, the file was left with Omar’s six, and the kettle was gone. Node does the file work outside your JavaScript’s thread, so both writes were under way at once. That isn’t what lost the kettle, though, because Omar’s copy never had it.
- No two lines of your code ran at the same moment. The requests took turns at their awaits, and that split each read from its write. When your tickets lived in an array in memory, the same script kept both, because pushing onto that array had no
awaitin the middle. - One thread doesn’t stop a race. A read, an
await, then a write can lose an update.
Here’s the script that sends both tickets at once, race.ts. Before each run, copy tickets.json from the course’s starting project, so it holds the five starting tickets again, even after a run that left it broken. Then start the app with node --watch app.ts, and run node race.ts from your second terminal. The script needs the app running, so its output below comes from a real run against it:
race.ts
const TICKETS_URL = "http://localhost:3000/tickets";
function post(name: string, item: string, fault: string) {
return fetch(TICKETS_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, item, category: "electrical", fault }),
});
}
const answers = await Promise.all([
post("Hana", "kettle", "Won't switch off"),
post("Omar", "fan", "Blades don't spin"),
]);
console.log(answers.map((answer) => answer.status));
const response = await fetch(TICKETS_URL);
if (!response.ok) {
console.log(response.status);
} else {
const page: unknown = await response.json();
if (typeof page === "object" && page !== null && "total" in page) {
console.log(page.total);
}
}