A small and performant library for communicating with Web Workers or Service Workers, using Promises. Post a message to the worker, get a message back.
- Tiny footprint (~700 bytes min+gz)
- Assumes you have a separate
worker.jsfile (easier to debug, better browser support)
npm install promise-worker
Inside your main bundle:
// main.jsvar PromiseWorker = ;var worker = 'worker.js';var promiseWorker = worker;promiseWorker;
// worker.jsvar registerPromiseWorker = ;;
Note that you
require() two separate APIs, so the library is split
worker.js and main file. This keeps the total bundle size smaller.
If you prefer
script tags, you can get
And inside the worker, you can get
The message you send can be any object, array, string, number, etc.:
Note that the message will be
JSON.stringifyd, so you
can't send functions,
Dates, custom classes, etc.
Inside of the worker, the registered handler can return either a Promise or a normal value:
Ultimately, the value that is sent from the worker to the main thread is also
stringifyd, so the same format rules apply.
Any thrown errors or asynchronous rejections from the worker will be propagated to the main thread as a rejected Promise. For instance:
Note that stacktraces cannot be sent from the worker to the main thread, so you
will have to debug those errors yourself. This library does however, print
console.error(), so you should see them there.
If you need to send messages of multiple types to the worker, just add some type information to the message you send:
Communicating with a Service Worker is the same as with a Web Worker. However, you have to wait for the Service Worker to install and start controlling the page. Here's an example:
Then inside your Service Worker:
var registerPromiseWorker = ;;self;
See .zuul.yml for the full list of tested browsers. Assuming you have a Promise polyfill, the supported browsers should be:
- Safari 8+
- IE 10+
- iOS 8+
- Android 4.4+
For Service Worker support, Chrome 40 and 41 are known to be buggy (see #9), but 42+ are supported.
This library is not designed to run in Node.js.
Create a new
PromiseWorker, using the given worker.
Workeror PseudoWorker to use.
Send a message to the worker and return a Promise.
message- object - required
- The message to send.
- returns a Promise
Register a message handler inside of the worker. Your handler consumes a message and returns a Promise or value.
- Takes a message, returns a Promise or a value.
Testing the library
Then to test in Node (using an XHR/PseudoWorker shim):
Or to test manually in your browser of choice:
npm run test-local
Or to test in a browser using SauceLabs:
npm run test-browser
Or to test with coverage reports:
npm run coverage