use-worker-directive
v0.6.1
Published
Universal "use worker" functions
Readme
use-worker-directive
Universal
use workerfunctions
Install
npm i use-worker-directiveyarn add use-worker-directivepnpm add use-worker-directiveFeatures
Worker functions
Like the original "use worker" directive, the compiler supports functions.
async function doStuff(x, y) {
"use worker";
await foo(x);
await bar(y);
}
// also works for arrow functions
const doStuff = async (x, y) => {
"use worker";
await foo(x);
await bar(y);
};The compiler also supports async generators
async function* doStuff(x, y) {
"use worker";
yield foo(x);
yield bar(y);
}NOTE Worker functions are only valid for async functions.
Worker blocks
The original "use worker" is limited to functions, but what if you could mark block statements with the same directives?
if (someCond()) {
'use stuff';
await doStuff();
}use-worker-directive supports worker blocks in almost all statements that supports it:
if-elsetry-catch-finallyforfor-infor-offor awaitwhiledo-while- labeled statements
Worker blocks also supports break, continue, return and throw statements, as well as yield expressions and delegations.
for (const item of items) {
'use worker';
await processItem(item);
}NOTE Worker blocks are only supported within async functions and at top-level scope (since modules now support top-level
await)
Closure extraction
use-worker-directive supports closure extraction
async function foo() {
const prefix = 'Message: ';
async function postMessage(message) {
'use worker';
await addMessage(prefix + message);
}
}Streaming worker functions
If a worker function returns a value with a Promise, ReadableStream or AsyncIterable, those instances' values are going to be streamed through the response.
async function getMessage() {
'use worker';
return {
// `getAsyncData` returns a Promise
// On the client-side, this object is going to
// be received immedatiely, but the value
// to which the Promise resolves into
// is going to be streamed after.
message: getAsyncData(),
};
}Advanced serialization
use-worker-directive supports a wide range of data types, you can check the compatibility table here
Customizable directive
Integrations
Sponsors
License
MIT © lxsmnsyc
