A partial archive of discourse.wicg.io as of Saturday February 24, 2024.

[Proposal] Context Managers in JavaScript


What is a Context Manager?

In general context managers are useful when we have a bunch of lines to be executed in a specific order. But more importantly they are used to release resources like Files, Database connections, memory etc. Here is a page from Python docs explaining their use and implementation.

Why do we need them in JavaScript?

I missed them the most when using Tensorflow.js where we explicitly release the resources regularly to restore memory for future operations. Checkout this function for example, from their docs, where they identify objects given an image or video stream. As they use webgl for faster execution of ML (or linear algebra) functions, they dispose them quite frequently like so,

// clean the webgl tensors

or with a custom function called tidy like so,

const batched = tf.tidy(() => {
    // process a variable from closure and clean up any intermediate tensors
    return img.expandDims(0);

If we don’t free them up, there is a high chance that the web page will crash after using up all the memory due to memory leaks. In fact, this is one of the most frequent challenges in using libraries like this properly.

Using Python’s and C#'s design philosophies the above code can be modified as,

const batched = new BatchedData( dataArray );
using( batched ) {
  // process batched
// batched is disposed automatically

or the JIT could detect the last usage of batched and dispose it, as it was marked for disposal

const batched = new BatchedData( dataArray );
using( batched ); // mark batched for disposal
     process batched
// batched is disposed automatically as it is no longer referenced going forward

I have seen work arounds for this using Promises [1, 2], but a native API is always a lot cleaner.

Besides ML, do you think it will be needed when APIs like File System become more mainstream? Where else can this be useful?


Also submitted this to https://webwewant.fyi/