[dead]
Re:Why Would Anyone Need JavaScript Generator Functions?
by qazxcvbnm on Tuesday November 08, 2022 @12:20AM
(#33516115)
OP's technique is useful for a consumer of a another function, to consume it in a synchronity-agnostic manner. In the implementation of the function consumer, you should find the usage of OP's technique.
In other words, this technique allows a library's implementation and interface to be synchronity-agnostic, but it does not say anything about the library user. If the library user likewise makes use of the OP technique, the library user code will remain synchronity-agnostic, otherwise it will be tied to be either synchronous or be asynchronous (parametrised to the synchronity).
If that's okay for your code, then go for it. However, downgrading a sync function to be async has serious performance implications - turning a trivial sync function call in a tight loop into an awaited async function call will make your loop 90%+ slower [benchmark]. You're also going to allocate much more memory for Promise objects. The code I linked above is from a library implementing a sandboxed Javascript VM. If we forced all calls into the guest sandbox, or from the guest sandbox back to host functions like `console.log`, to be async, the VM would be unusable for many applications.
[MDN for await]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
[benchmark]: https://jsbench.me/y0la7auape/2