Skip to content

Instantly share code, notes, and snippets.

@a10y
Created August 16, 2022 02:41
Show Gist options
  • Save a10y/9179ee7e45af838ea33b8e1b856a908c to your computer and use it in GitHub Desktop.
Save a10y/9179ee7e45af838ea33b8e1b856a908c to your computer and use it in GitHub Desktop.
Deno webworker example
import { serve } from "https://deno.land/std@0.140.0/http/server.ts";
serve(async (request) => {
const worker = new Worker(new URL("./worker.ts", import.meta.url).href, {
type: "module",
name: "worker-" + (100 * Math.random()).toFixed(),
});
const data = await request.json();
console.log("new task", data);
worker.postMessage({ task: data });
// Wait for a response from the worker to be fulfilled
// Fulfill the promise when the mesage is passed.
const result = new Promise((resolve, reject) => {
worker.onmessage = (msg) => {
resolve(msg.data);
};
worker.onerror = (err) => {
err.preventDefault();
reject(err.message);
};
});
return result.then((output) => Response.json({ result: output }))
.catch((reason) => {
console.log("Caught reason");
return Response.json({
reason,
}, {
status: 400,
});
})
.finally(() => worker.terminate());
}, {
port: 9090,
});
console.log("server started @ 0.0.0.0:9090");
/**
* This worker can do one of two things: simple calculator or print things to console.
*/
export type WorkerParams =
| CalculatorParams
| PrinterParams;
export type Operation =
| "add"
| "subtract";
export interface CalculatorParams {
type: "calculator";
x: number;
y: number;
op: Operation;
}
export interface PrinterParams {
type: "printer";
text: string;
}
/**
* Do worker things
*/
import { CalculatorParams, PrinterParams, WorkerParams } from "./types.ts";
// Install the app ID in the current environment.
const APP_ID = Deno.env.get("APP_ID")!;
console.log("worker starting");
self.onmessage = async (evt) => {
const { task }: { task: WorkerParams } = evt.data;
console.log("worker received task", task);
switch (task.type) {
case "calculator":
self.postMessage(handleCalculator(task));
return;
case "printer":
self.postMessage(handlePrinter(task));
return;
default:
throw new Error("Invalid task type!");
}
};
function handleCalculator(calculator: CalculatorParams) {
switch (calculator.op) {
case "add":
return { result: calculator.x + calculator.y };
case "subtract":
return { result: calculator.x - calculator.y };
}
}
function handlePrinter(printer: PrinterParams) {
return printer.text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment