JavaScript traps · Chapter 1 of 16

A missing await

Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Everyday traps
  • 3 tasks
  • JavaScript
  • Free chapter

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.

Why you need this

A promise is an object, and in an if, every object counts as true, whatever it will resolve to later:

const mint = inStock('mint');
console.log(typeof mint, Boolean(mint), !mint);
console.log(Boolean(await mint));
object true false
false

So code that forgets the await does not crash, does not warn and prints nothing odd. It takes the wrong branch, quietly, every time. That is why the ticket has no error in it, only a log in the wrong order.

The lesson

By the end of this case

You can tell a missing await from its symptoms, make it happen on purpose with a fake that answers on command, fix it, and pin it down with a test that fails on the bug and passes on the fix.

The ticket

TAP-311: Orders going out to riders unpaid. Assigned to you by Kabir. Priority: high. Since: Tuesday's release.

Ravi, in the ops channel at 6:40 pm: "Three riders went out today with orders nobody had paid for. 1042 was Imran's, ₹215 of masala chai and bun maska to Indiranagar. The bank declined the UPI payment and the app sent the rider anyway. Before Tuesday this never happened."

The dispatch log for order 1042, with the UPI gateway's lines beside it:

16:02:11.204  dispatch  order 1042: sent to Imran
16:02:13.870  upi       order 1042: FAILED, declined by bank

Kabir: "Tuesday's release changed one thing in dispatch: isPaid used to read the morning's payment cache, and now it asks the UPI gateway live, so it became async. Look at the times: the rider went out 2.6 seconds before the bank answered. And since Tuesday the log has not held a single order. Reproduce it first, then fix it, then make sure it can never come back. You are in dispatch.js."

What an async function hands back

An async function never hands back its value. It hands back a promise of the value, straight away, and the value comes later. Here is a stock check of the same kind, with mint sold out:

const stock = { getLeft: async (item) => ({ ginger: 4, mint: 0 })[item] };

async function inStock(item) {
  const left = await stock.getLeft(item);
  return left > 0;
}

const answer = inStock('mint');
console.log(answer);
console.log(await answer);
Promise { <pending> }
false

answer is the promise. Only await answer gives the false inside it.

Making it happen on purpose

A bug you can only see in production is a bug you cannot fix with confidence. So you reproduce it first, on your laptop, every time: you replace the real gateway with a fake, a plain object with the same method names that answers whatever you decide. No bank, no network, no waiting.

A fake can even hold its answer back until you say so. This is how the check makes sure code waits for a slow service before it decides:

let answer;
const stock = {
  getLeft: (item) => new Promise((resolve) => { answer = resolve; }),
};

async function reorderIfLow(item) {
  const left = await stock.getLeft(item);
  if (left < 5) return 'reordered';
  return 'enough';
}

reorderIfLow('ginger').then((r) => console.log('decided:', r));
console.log('asked the stock service');
await Promise.resolve();
console.log('still waiting, nothing decided');
answer(4);
asked the stock service
still waiting, nothing decided
decided: reordered

Nothing is decided until the fake answers. Code that decides before that has a missing await somewhere.

A test that would have caught it

A guard test turns the repro into something that runs before every release. The lab has vitest: it names one test, expect checks a value, and vi.fn makes a fake function that remembers its calls. Here stock.js takes the stock service as its first value, so a test can hand it a fake:

// stock.js
export async function inStock(stock, item) {
  const left = await stock.getLeft(item);
  return left > 0;
}
// stock.test.js
import { it, expect, vi } from 'vitest';
import { inStock } from './stock.js';

it('says no when nothing is left', async () => {
  const stock = { getLeft: vi.fn(async () => 0) };
  expect(await inStock(stock, 'mint')).toBe(false);
  expect(stock.getLeft).toHaveBeenCalledWith('mint');
});

Run from the workspace folder, it passes (output trimmed):

$ npx vitest run chapters/stock-demo
 ✓ chapters/stock-demo/stock.test.js (1 test) 3ms
 Test Files  1 passed (1)

Slip a bug into inStock (left >= 0) and the same test stops it (trimmed):

 FAIL  chapters/stock-demo/stock.test.js > says no when nothing is left
AssertionError: expected true to be false // Object.is equality

 Test Files  1 failed (1)
      Tests  1 failed (1)

A good guard fails on the bug and passes on the fix. A test that fails on everything proves nothing, and so does one that only checks one side: code that holds every order would never send an unpaid one out either.

Your turn

Three tasks, one file each. In repro.js, make an unpaid order go out on purpose, and run it with node repro.js in the case's folder. In dispatch.js, fix the bug. In dispatch.test.js, write the guard: the check runs it beside the original code, the fix and a wrong fix that holds every order. Then answer Kabir's interview question at the bottom of the case, in your own words.

What you build: 3 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    repro.js: send an unpaid order out on purpose

    Write reproduce() in repro.js. Build a fake UPI gateway, an object whose getPayment(orderId) resolves to { orderId, status: 'FAILED' } for any order, and a fake riders object whose assign(order) resolves to a rider's name. Call dispatchOrder(order, { upi, riders }) from dispatch.js with an order (any id and area) and the two fakes, and resolve to what dispatchOrder resolved to.

    The check runs your reproduce() twice: beside the original dispatch.js it must resolve to 'dispatched' (an unpaid order went out), and beside a fixed dispatch.js it must resolve to 'held'. So it must really call dispatchOrder with a failed payment. No real waiting: the fakes answer straight away, and reproduce() must finish within 2 seconds.

  2. Task 2

    dispatch.js: no rider until the bank says yes

    Fix dispatchOrder(order, { upi, riders }) in dispatch.js. It must wait for the payment's answer before it decides. When the payment's status is SUCCESS, it books a rider with riders.assign(order), exactly once, logs order <id>: sent to <rider> and resolves to 'dispatched'. When the status is FAILED or PENDING, it books no rider, logs order <id>: held, payment not received and resolves to 'held'.

    No rider may be booked, and nothing decided, while the gateway has not answered yet: the check holds the gateway's answer back and looks. Keep isPaid and the two log lines as they are. The check uses its own orders, not 1042, and a fix that holds every order is as wrong as the bug.

  3. Task 3

    dispatch.test.js: a test that would have caught it

    Write a vitest test file, dispatch.test.js, that would have caught this bug before the release. The check runs your file three times: beside the original dispatch.js, where at least one test must fail; beside the fixed dispatch.js, where every test must pass; and beside a wrong fix that holds every order, paid ones too, where at least one test must fail.

    So test both sides with fake gateways and fake riders, as in your repro: an order whose payment is FAILED resolves to 'held' and gets no rider, and an order whose payment is SUCCESS resolves to 'dispatched'. No real waiting: each test must finish within 3 seconds.

What you will learn

  • repro.js: send an unpaid order out on purpose
  • dispatch.js: no rider until the bank says yes
  • dispatch.test.js: a test that would have caught it

More in Everyday traps

Build "A missing await" yourself

Tapri runs on JavaScript, and Kabir, its senior developer, keeps assigning you tickets. Each is a real trap interviews love to ask about. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.