- Notifications
You must be signed in to change notification settings - Fork99
🦎 Move an async function into its own thread.
developit/greenlet
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Move an async function into its own thread.
A simplified single-function version ofworkerize, offeringthe same performance as direct Worker usage.
The name is somewhat of a poor choice, but it wasavailable on npm.
Greenlet supports IE10+, since it usesWeb Workers. For NodeJS usage, Web Workers must be polyfilled using a library likenode-webworker.
npm i -S greenlet
Accepts an async function with, produces a copy of it that runs within a Web Worker.
⚠️ Caveat: the function you pass cannot rely on its surrounding scope, since it is executed in an isolated context.
greenlet(Function) -> Function
‼️ Important: never call greenlet() dynamically. Doing so creates a new Worker thread for every call:
-const BAD = () => greenlet(x => x)('bad') // creates a new thread on every call+const fn = greenlet(x => x);+const GOOD = () => fn('good'); // uses the same thread on every call
Since Greenlets can't rely on surrounding scope anyway, it's best to always create them at the "top" of your module.
Greenlet is most effective when the work being done has relatively small inputs/outputs.
One such example would be fetching a network resource when only a subset of the resulting information is needed:
importgreenletfrom'greenlet'letgetName=greenlet(asyncusername=>{leturl=`https://api.github.com/users/${username}`letres=awaitfetch(url)letprofile=awaitres.json()returnprofile.name})console.log(awaitgetName('developit'))
Greenlet will even accept and optimizetransferables as arguments to and from a greenlet worker function.
Thankfully, Web Workers have been around for a while andare broadly supported by Chrome, Firefox, Safari, Edge, and Internet Explorer 10+.
If you still need to support older browsers, you can just check for the presence ofwindow.Worker:
if(window.Worker){ ...}else{ ...}
If your app has aContent-Security-Policy, Greenlet requiresworker-src blob: andscript-src blob: in your config.
In addition to the contributors, credit goes to@sgb-io for his annotated exploration of Greenlet's source. This prompted a refactor that clarified the code and allowed for further size optimizations.
About
🦎 Move an async function into its own thread.
Topics
Resources
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors11
Uh oh!
There was an error while loading.Please reload this page.
