From Python's with to JavaScript's using and try/finally (Summary)

Priya’s job runner now uses JavaScript next to Inkwell & Co.’s order-tracking app. Each morning it acquires every job’s lock, spools the artwork, sends it to press-1 or press-2, and releases each job’s resources, even when a job fails halfway. And it still leaves the other PC’s J-314.lock exactly where it found it.

In Python, with and its context managers made that cleanup automatic. JavaScript’s tools for it are newer, and they differ in details that matter when porting code: where the acquiring line goes, how long a resource is held, and what gets awaited. In this course, you learned how to:

  • Release a resource with try/finally, acquiring it on the line before the try.
  • Recognize calls that manage files they open from paths, such as readFile(), writeFile(), and copyFileSync(). Identify resources you must close: caller-supplied handles or descriptors, a FileHandle from open(), a timer from setInterval(), and a connection like the print queue’s.
  • Give a class a [Symbol.dispose]() method and hold an instance with using in a block that lasts as long as the with block did.
  • Replace a function decorated with @contextmanager with a function that returns a disposable object.
  • Close a connection with await using and [Symbol.asyncDispose](), with its asynchronous setup in a static async factory such as PrinterQueue.connect().
  • Collect a changing set of resources with an AsyncDisposableStack, using stack.use() for each queue and stack.defer() for the spool folder.

Those pieces add up to the runner’s main(), which opens only the queues the morning needs and closes them in reverse order when its block ends.

Habits to Keep

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.