astoilkov / main-thread-scheduling

Fast and consistently responsive apps using a single function call
MIT License
1.29k stars 32 forks source link

Don’t crash SSR #3

Closed ScriptedAlchemy closed 2 years ago

ScriptedAlchemy commented 2 years ago

I'm currently using a conditional to opt out on the server. But it would be less risky if on node it just performs a pass through.

I've also had some problems with jest clear timers getting stuck in a infinite loop if MTS is used on one of those unit tested components

It could be useful if node_env is set to test, do something like resolve a promise with a setTimeout. This may also help with other things like some of my tests "fail" because X function I'm spying on wasn't called fast enough.

astoilkov commented 2 years ago

It makes sense. What I am asking myself is "Is it possible to do it outside of the library?". You can make an abstraction that wraps the original methods and trigger different behavior depending on node_env and node.

I believe this is beneficial in the early stages of a library because it doesn't add complexity for all users. If, with time, we understand that this requirement is universal and commonly encountered then we can add it to the library itself.

What do you think? Does it make sense?

ScriptedAlchemy commented 2 years ago

Yeah it can be mitigated outside the library via an abstraction. But in general its nice to have universal compatibility or something like

typeof window === "undefined" then just call the callback right away instead

An abstraction would totally work, or perhaps even an export from this lib for like universalYield

astoilkov commented 2 years ago

Quick question. Are you using React and server-side rendering together with it? How does yieldControl() is called while rendering? Can you give sample code?

ScriptedAlchemy commented 2 years ago

Usually I just short circuit it during SSR so it always runs immediately. I also already can support async on my renders. So I have fetch calls any other side effects the server picks up and handles.

astoilkov commented 2 years ago

I will be implementing this.

astoilkov commented 2 years ago

This is now implemented in version 7. Calling main-thread-scheduling in tests will return a Promise.resolve().