close
close

How to use the Context Manager pattern in JavaScript for efficient code execution

While working on a project today, I came across a use case where I needed to perform an operation at both the beginning and end of a function. This scenario was also reflected in many other functions. After some research I came across the Context Manager pattern, which is often used in Python to handle install and cleanup operations around code execution.
However, since I work in JavaScript, I’ve been exploring ways to implement a similar pattern. In this post I will share some of these methods.

1. Using functions with try/finally

You can create a function that accepts another function as a parameter, performs the setup for it, and performs the cleanup afterward using try And finally.

function contextManager(doWork) {
  console.log('Setup: entering the context');

  try {
    doWork();
  } finally {
    console.log('Cleanup: leaving the context');
  }
}

// Using the context manager
contextManager(() => {
  console.log('Doing some work inside the context');
});

Go to full screen mode

Exit full screen mode

Exit

Setup: entering the context
Doing some work inside the context
Cleanup: leaving the context

Go to full screen mode

Exit full screen mode

2. Using a class with a try/final

If you prefer an OOP approach, you can also implement this pattern using a class.

class ContextManager {
  enter() {
    console.log('Setup: entering the context');
  }

  exit() {
    console.log('Cleanup: leaving the context');
  }

  run(fn) {
    this.enter();
    try {
      fn();
    } finally {
      this.exit();
    }
  }
}

// Usage
const manager = new ContextManager();
manager.run(() => {
  console.log('Doing some work inside the context');
});

Go to full screen mode

Exit full screen mode

3. Using Contextlib library

This contextlib library in JavaScript provides a Python-like statement for managing resource setup and cleanup using objects with enter And exit methods.

const { With } = require("contextlib");

class Manager {
    enter() {
        console.log("setting up...");
    }
    exit() {
        console.log("cleaning up...")
    }
}

// Usage
With(new Manager(), () => {
    console.log("inside context");
})
Go to full screen mode

Exit full screen mode

Export

setting up...
inside context
cleaning up...
Go to full screen mode

Exit full screen mode

In this post, we explored how to implement the Context Manager pattern in JavaScript, inspired by its use in Python. By using different approaches including functions with try/finallyclasses and the contextlib library, you can effectively manage the installation and cleanup operations around your code. This pattern not only improves code readability, but also ensures resources are handled properly, making your applications more robust and error-resistant.

By applying these techniques, you can simplify your code and create a more organized structure for managing resource-intensive tasks. Whether you prefer a functional or an object-oriented approach, there is a method that suits your coding style.

I encourage you to experiment with these patterns in your own projects and see how they can improve your code management. If you have any opinions, questions, or additional methods to share, please leave a comment below. Happy coding!🚀