Loading video player…

Seeing the Promise Behind an Async Call

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):

Language: Python
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:

Language: Program Output
<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:

Language: JavaScript
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:

Language: Program Output
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:

Language: JavaScript
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:

Language: Program Output
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:

Language: JavaScript
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:

Language: Program Output
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.

00:00 Your port of checkKiosk() awaits its answer at the top level. But what is await waiting for? To find out, call the function without await, and log what comes back.

00:13 In Python first, check_kiosk() now prints asking and the branch as it starts. main() calls it without await, prints the result and Checking kiosks, then awaits it last.

00:26 Python prints a coroutine object, then Checking kiosks. Only at the await does it ask Northgate, and the holds come back.

00:36 In the JavaScript port, checkKiosk() logs the same line as it starts. The call without await keeps what it returns in a const.

00:46 Then two logs, as in Python.

00:50 The await moves to the top level, where your port already waits, so there’s no main() to wrap it. The last line logs Northgate’s holds.

01:01 Run the port. JavaScript logs asking Northgate first. The call ran checkKiosk() up to its first await, the sleep, then handed back a promise.

01:13 The log of northgate shows it, pending. Then Checking kiosks, and after the await, Northgate’s 14 holds. Watch out: in JavaScript, the call starts the work, so asking Northgate comes before Checking kiosks.

01:32 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. A JavaScript call runs either way, which matters later in the course.

01:48 A promise is a placeholder for a result that isn’t ready yet. It starts pending. Now log northgate again, after the await. What does it show?

02:01 Your turn: pause the video and predict.

02:09 A promise holding Northgate’s record.

02:13 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, which is how kiosk gets Northgate’s record.

02:32 That makes a promise closer to an asyncio Task than to a coroutine: a Task also runs without an await, and keeps its result.

02:42 But a Task needs a create_task() step, and doesn’t start until main() next pauses. A promise is already under way when the call returns.

02:52 The promise isn’t the value. Watch out: leave the await out, and a template literal shows [object Promise], and the holds property is undefined, the same slip as forgetting await on a file read.

03:07 A promise can also fail. Quarry Hill’s new kiosk fails its first answer of the morning, so its stand-in throws an error, where Python’s raises one. It joins the list in the next section: here it’s checked on its own.

03:24 When the function throws, its promise is rejected with that error. await then throws that error, so a try around the await catches it, as in Python.

03:35 Both print the message. Log the promise afterwards: catching the error didn’t change it. It’s still rejected, with the error and its stack.

03:48 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 one for the error.

03:59 Had Quarry Hill answered, the .then() callback would get its record. It fails, so the .catch() callback logs the same message.

04:09 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.

04:23 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.

04:40 Next up, 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 Python’s lines for Northgate and Eastfield.

Become a Member to join the conversation.