'Any tips on context manager similar to Python in Javascript?

I quite liked Python's context manager where I did not have to be concerned with how the resource was obtained or cleaned up afterwards. Is there a way to do this in a neat way in Javascript?



Solution 1:[1]

I also surprised by missing this feature. Unfortunately, only callback based solutions are available in JS

https://promise-nuggets.github.io/articles/21-context-managers-transactions.html

Solution 2:[2]

I'm happy to break this to you, we now have that in JavaScript. It's a tiny library called "contextlib" (closely resembling python's contexlib).

Disclaimer: I authored contextlib.

You can install using npm install contextlib.

import {With, contextmanager} from 'contextlib';

class context:
    enter() { console.log('entering context') }

    exit() { console.log('leaving context') }

With(new context(), () => {
   console.log('inside context')
})

You can also use the contextmanager decorator

context = contextmanager(function*(){
    try {
        console.log('entering context')
        yield
    } finally {
        console.log('leaving context')
    }
})

You should check it out on github.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kmmbvnr
Solution 2 Dave