proposal-async-context icon indicating copy to clipboard operation
proposal-async-context copied to clipboard

Using AsyncContext for globals?

Open slorber opened this issue 1 year ago • 0 comments

It's a crazy idea. I'm not sure this discussion belongs to this repo, but this feels related so I'm giving it a try.

Fact: people patch globals

Over the years, countless people have patched/extended globals of their JS runtime.

More recently, React and Next.js patching fetch() in Server Components environment to add caching let to controversy and the feature has been removed.

Proposed idea: use AsyncContext for globals

What if we could do local dependency injection of globals?

What if we could enable libs/frameworks to alter globals safely for a whole execution flow, that is convenient, and yet does not need to modify the underlying runtime?

What if we could improve the testability of apps using globals at the same time, as an alternative to solutions such as Mock Service Worker?

Example implementation

This is just pseudo code but I think this kind of API could be interesting to have:

// This uses runtime global fetch
const result = await fetch("/user");

AsyncContext.Globals.run(
  // Provides custom fetch for the underlying execution flow
  { fetch: myCustomFetch },
  async () => {
    // This uses the custom fetch
    const result = await fetch("/user");

    AsyncContext.Globals.run(
      // Reverts the custom fetch for the underlying execution flow
      { fetch: null },
      async () => {
        // This uses runtime global fetch
        const result = await fetch("/user");
      },
    );
  },
);

slorber avatar Apr 25 '24 14:04 slorber