|
|
|
|
|
by jitl
1324 days ago
|
|
It's very easy to make sync code async. Just add an `async` to the function declaration. You don't need the `instanceof` check or `Promise.resolve` - you can `await` any type of value; it'll get unwrapped as a Promise if it has a `then` method, or otherwise just give you back the value. See [MDN for await]. 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 |
|