Closing a Connection With await using

Your port’s runJob() now hands the lock and the spool copy to using, so each one releases itself when its block ends. You still close the print queues by hand. In main(), an inner try runs the morning’s jobs, and its finally awaits press2.close() and then press1.close().

Priya’s Python needs no finally for the queues, because each one is an async context manager. A queue takes a moment to close, so [Symbol.dispose]() won’t do: using calls it and moves on without waiting. In this lesson, you’ll give the queue a cleanup method that JavaScript waits for and open each queue with one declaration.

Give the Queue an Async Dispose Method

Start with the class. In runner.py, PrinterQueue connects in __aenter__() and closes in __aexit__(). Both methods are coroutines, so async with awaits one on the way in and the other on the way out:

Language: Python
import asyncio
import contextlib

class PrinterQueue:
    def __init__(self, press):
        self.press = press

    async def __aenter__(self):
        await asyncio.sleep(0.01)
        self.heartbeat = asyncio.create_task(self._beat())
        print(f"[queue] connected to {self.press}")
        return self

    async def _beat(self):
        while True:
            await asyncio.sleep(1)

    async def send(self, spool, copies):
        await asyncio.sleep(0.01)
        print(f"  [queue] {self.press} accepted {spool.name} x {copies}")

    async def __aexit__(self, *exc_info):
        self.heartbeat.cancel()
        with contextlib.suppress(asyncio.CancelledError):
            await self.heartbeat
        print(f"[queue] closed {self.press}")

JavaScript’s protocol has only the release half. Next to Symbol.dispose, it has a second built-in symbol, Symbol.asyncDispose, for a release that returns a promise. An object with a [Symbol.asyncDispose]() method is an async disposable, the counterpart of an object with __aexit__().

Copy your port to runner-s3.js for this stage. The only change to the class is that its async close() method becomes async [Symbol.asyncDispose](), with the same body:

Language: JavaScript
import { setTimeout as sleep } from "node:timers/promises";

class PrinterQueue {
  constructor(press) {
    this.press = press;
    this.heartbeat = setInterval(() => {}, 1000);
  }

  static async connect(press) {
    await sleep(10);
    const queue = new PrinterQueue(press);
    console.log(`[queue] connected to ${press}`);
    return queue;
  }

  async send(spool, copies) {
    await sleep(10);
    const line = `${this.press} accepted ${spool.name} x ${copies}`;
    console.log(`  [queue] ${line}`);
  }

  async [Symbol.asyncDispose]() {
    clearInterval(this.heartbeat);
    await sleep(10);
    console.log(`[queue] closed ${this.press}`);
  }
}

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.