UNPKG

@kuiu/task-worker

Version:

task worker

72 lines (51 loc) 2.29 kB
# TaskWorker(任务调度器) TaskWorker makes [WebWorkers][webworker] enjoyable. TaskWorker is a **tiny library (1.1kB)**, that removes the mental barrier of thinking about `postMessage` and hides the fact that you are working with workers. At a more abstract level it is an RPC implementation for `postMessage` and [ES6 Proxies][es6 proxy]. ``` $ npm install --save @kuiu/task-worker ``` ## Introduction On mobile phones, and especially on low-end mobile phones, it is important to keep the main thread as idle as possible so it can respond to user interactions quickly and provide a jank-free experience. **The UI thread ought to be for UI work only**. WebWorkers are a web API that allow you to run code in a separate thread. To communicate with another thread, WebWorkers offer the `postMessage` API. You can send JavaScript objects as messages using `myWorker.postMessage(someObject)`, triggering a `message` event inside the worker. TaskWorker turns this messaged-based API into a something more developer-friendly by providing an RPC implementation: Values from one thread can be used within the other thread (and vice versa) just like local values. **main.js** ```javascript import * as TaskWorker from "@kuiu/task-worker"; async function init() { // WebWorkers use `postMessage` and therefore work with TaskWorker. const obj = TaskWorker.createTaskPorxy([new Worker("worker.js"), new Worker("worker.js")], [], null, true); alert(`Counter: ${await obj.counter}`); await obj.initial(); alert(`Counter: ${await obj.counter}`); } init(); ``` **worker.js** ```javascript const obj = { counter: 0, inc() { this.counter++; }, }; const Worker = new TaskWorker.TaskWorker(self) Worker.expose('default', obj); ``` **main.js** ```javascript function callback(value) { alert(`Result: ${value}`); } async function init() { const remoteFunction = TaskWorker.createTaskPorxy([new Worker("worker.js")], [], null, true); await remoteFunction(TaskWorker.proxy(callback)); } init(); ``` **worker.js** ```javascript async function remoteFunction(cb) { await cb("A string from a worker"); } const Worker = new TaskWorker.TaskWorker(self) Worker.expose('default', remoteFunction); ```