DEV Community

Cover image for How to Use Context Manager Pattern in JavaScript for Efficient Code Execution
Vishnu Satheesh
Vishnu Satheesh

Posted on

How to Use Context Manager Pattern in JavaScript for Efficient Code Execution

Today, while working on a project, I encountered a use case where I needed to perform an operation at both the start and end of a function. This scenario was recurring in many other functions as well. After some research, I came across the Context Manager pattern, which is commonly used in Python to handle setup and cleanup operations around code execution.
However, since I'm working in JavaScript, I explored ways to implement a similar pattern. In this post I will share some of those methods.

1. Using Functions with try/finally

You can create a function that accepts another function as a parameter, performs setup before it, and cleanup after it 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');
});

Enter fullscreen mode Exit fullscreen mode

output

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

Enter fullscreen mode Exit fullscreen mode

2. Using a Class with a try/finally

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');
});

Enter fullscreen mode Exit fullscreen mode

3. Using contextlib library

This contextlib library in JavaScript provides a Python-like with 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");
})
Enter fullscreen mode Exit fullscreen mode

Output

setting up...
inside context
cleaning up...
Enter fullscreen mode Exit fullscreen mode

In this post, we've explored how to implement the Context Manager pattern in JavaScript, inspired by its usage in Python. By using various approaches, including functions with try/finally, classes, and the contextlib library, you can effectively manage setup and cleanup operations around your code. This pattern not only enhances code readability but also ensures that resources are properly handled, 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's a method to suit 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!🚀

Top comments (0)