Seeing the Promise Behind an Async Call
Your port of checkKiosk() awaits its answer at the top level. To see what await is waiting
for, call the function without await and log what comes back. In Python first, check_kiosk()
now prints asking and the branch as it starts (the import and KIOSKS are as before):
async def check_kiosk(branch):
print(f"asking {branch}")
kiosk = KIOSKS[branch]
await asyncio.sleep(kiosk["delay"])
return {"branch": branch, "holds": kiosk["holds"]}
async def main():
northgate = check_kiosk("Northgate")
print(northgate)
print("Checking kiosks")
kiosk = await northgate
print(f"{kiosk['branch']}: {kiosk['holds']} holds waiting")
if __name__ == "__main__":
asyncio.run(main())
Python prints a coroutine object, then Checking kiosks, and only asks Northgate at the await:
<coroutine object check_kiosk at 0x7f203f317060>
Checking kiosks
asking Northgate
Northgate: 14 holds waiting
In the JavaScript port, the await moves to the module’s top level, where your port already
waits, and a last line logs northgate again:
import { setTimeout as sleep } from "node:timers/promises";
const KIOSKS = {
Northgate: { delay: 120, holds: 14 },
Eastfield: { delay: 250, holds: 9 },
"Hollins Green": { delay: 900, holds: 6 },
};
async function checkKiosk(branch) {
console.log(`asking ${branch}`);
const kiosk = KIOSKS[branch];
await sleep(kiosk.delay);
return { branch, holds: kiosk.holds };
}
const northgate = checkKiosk("Northgate");
console.log(northgate);
console.log("Checking kiosks");
const kiosk = await northgate;
console.log(`${kiosk.branch}: ${kiosk.holds} holds waiting`);
console.log(northgate);
JavaScript asks Northgate first, and the call hands back a promise:
asking Northgate
Promise { <pending> }
Checking kiosks
Northgate: 14 holds waiting
Promise { { branch: 'Northgate', holds: 14 } }
The call ran checkKiosk() up to its first await, the sleep, then handed back a pending
promise.
Watch out: in JavaScript, the call starts the work, so asking Northgate comes before
Checking kiosks. Python’s call only built a coroutine, and asked at the await. A Python
coroutine that’s never awaited never runs, and Python warns you with RuntimeWarning: coroutine
'check_kiosk' was never awaited. A JavaScript call runs either way, which matters later in the
course.
A promise is a placeholder for a result that isn’t ready yet. It starts pending. Logged after
the await, it holds Northgate’s record: when the function returned, the promise was fulfilled
with the return value. A promise settles, fulfilled or rejected, only once, so it keeps that
value. await waits for that, then hands the value over.
That makes a promise closer to an asyncio Task than to a coroutine: a Task also runs without
an await, and keeps its result. But a Task needs a create_task() step, and by default doesn’t
start until main() next pauses (an eager Task, create_task(..., eager_start=True), behaves like
the promise here). A promise is already under way when the call returns.
The promise isn’t the value. Watch out: leave the await out, and ${checkKiosk("Northgate")}
shows [object Promise] and checkKiosk("Northgate").holds is undefined, the same slip as
forgetting await on a file read.
A promise can also fail. Quarry Hill’s new kiosk, which joins the list in the next section, fails
its first answer of the morning, so its stand-in throws an error where Python’s raises
ConnectionError. When the function throws, its promise is rejected with that error, and await
throws it, so a try around the await catches it, as in Python:
import { setTimeout as sleep } from "node:timers/promises";
const KIOSKS = {
Northgate: { delay: 120, holds: 14 },
Eastfield: { delay: 250, holds: 9 },
"Hollins Green": { delay: 900, holds: 6 },
"Quarry Hill": { delay: 80, holds: 3, failsFirst: true },
};
async function checkKiosk(branch) {
console.log(`asking ${branch}`);
const kiosk = KIOSKS[branch];
await sleep(kiosk.delay);
if (kiosk.failsFirst) {
kiosk.failsFirst = false;
throw new Error(`${branch} kiosk is not answering`);
}
return { branch, holds: kiosk.holds };
}
const quarryHill = checkKiosk("Quarry Hill");
try {
await quarryHill;
} catch (err) {
console.log(err.message);
}
Both languages print the same two lines:
asking Quarry Hill
Quarry Hill kiosk is not answering
Catching the error doesn’t change the promise: log quarryHill after that, and the console
shows Promise { <rejected> Error: Quarry Hill kiosk is not answering ... }, with the error’s
stack inside the braces.
These examples use a macOS home path. Linux paths look like /home/you/...; Windows paths look like C:\Users\you\....
Older code and some libraries don’t await a promise: they call its methods. The .then()
method takes a callback for the value, and the .catch() method takes one for the error. Had
Quarry Hill answered, the .then() callback would get its record. With the same KIOSKS and
checkKiosk(), this chain logs the same message for Quarry Hill:
import { setTimeout as sleep } from "node:timers/promises";
const KIOSKS = {
Northgate: { delay: 120, holds: 14 },
Eastfield: { delay: 250, holds: 9 },
"Hollins Green": { delay: 900, holds: 6 },
"Quarry Hill": { delay: 80, holds: 3, failsFirst: true },
};
async function checkKiosk(branch) {
console.log(`asking ${branch}`);
const kiosk = KIOSKS[branch];
await sleep(kiosk.delay);
if (kiosk.failsFirst) {
kiosk.failsFirst = false;
throw new Error(`${branch} kiosk is not answering`);
}
return { branch, holds: kiosk.holds };
}
checkKiosk("Quarry Hill")
.then((kiosk) => console.log(kiosk))
.catch((err) => console.log(err.message));
It prints what the try block printed:
asking Quarry Hill
Quarry Hill kiosk is not answering
In your own code, write await: it reads top to bottom, like Python. .catch() comes back later
in the course. Wrapping old callback code in a promise yourself is a later topic.
In JavaScript, calling an async function starts it and hands back a promise. await only waits:
it gives you the value, or throws the error. So await the promise where you need the value, and
expect the work to be running already.
Next up is Port the Overnight Returns Check. Each branch’s returns machine counts the books dropped off overnight. You’ll take a teammate’s port of its check and get it printing the Python’s lines for Northgate and Eastfield.