Skip to content

Using AsyncContext for globals? #84

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
slorber opened this issue Apr 25, 2024 · 1 comment
Closed

Using AsyncContext for globals? #84

slorber opened this issue Apr 25, 2024 · 1 comment

Comments

@slorber
Copy link

slorber commented Apr 25, 2024

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");
      },
    );
  },
);
@legendecas
Copy link
Member

Thanks for sharing! This is an interesting use case. I believe this could be built in userland based on the necessary capability AsyncContext provides. Also, I'd find that this would be a use case that doesn't expect the values to be changed around await calls, mentioned in #83.

I'm closing this since this is an extension could be done in userland. Please feel free to re-open if you find it is not the case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants