Turning a @contextmanager Into a Disposable

Your port of Priya’s runner now holds each job’s lock with using, but the spool copy still goes the long way: runJob() copies the artwork by hand and wraps send() in a try/finally of its own. Priya’s Python never needed a class for that copy. She uses spooled(), a short @contextmanager function, and you’ll port it to return a disposable, so the copy gets a using line too.

Return the Copy With Its Cleanup

Here’s Priya’s spooled():

Language: Python
import shutil
from contextlib import contextmanager
from pathlib import Path

ART = Path("art")

@contextmanager
def spooled(job, folder):
    path = folder / f"{job['id']}.pdf"
    shutil.copy(ART / job["art"], path)
    print(f"  [spool] wrote {path.name}")
    try:
        yield path
    finally:
        path.unlink()
        print(f"  [spool] removed {path.name}")

JavaScript has no decorator for this. It doesn’t need one, because using reads [Symbol.dispose] like any other property, so a function can return an object literal. Each piece of the generator has a place in the port:

Python @contextmanager JavaScript function
Code before yield Code before return
yield path return { name, path, [Symbol.dispose]() { ... } }
The finally block The body of [Symbol.dispose]()
with spooled(job, folder) as spool: using spool = spooled(job, folder);

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.