message-bridge
TypeScript icon, indicating that this package has built-in type declarations

0.0.7 • Public • Published

message-bridge

Bridges class function calls between two contexes(workers) with messages.

Install

npm install --save message-bridge
Also contains an amd bundle you can use with systemjs and requirejs.

Usage

I built this library for communication with a web worker.
Let say we want to implement this communication to the web worker.

// The service that runs on the worker.
class Service {
    public getTrue(): boolean {
        return true; 
    }
 
    public addAsync(a: number, b: number): Promise<number> {
        return new Promise(resolve => { setTimeout(() => resolve(a + b), 1); });
    }
}
 
// Create the bridge interface (return promise for sync functions).
interface ServiceBridge {
    getTrue(): Promise<boolean>;
    addAsync(a: number, b: number): Promise<number>;
}
 
let channel = /* Find a way to create your channel (MessageChannel or just use the worker itself) */;
 
// At your main program:
let servicePromise: Promise<ServiceBridge> = ServiceToMessageBridge.create(channel.port1);
 
// At the worker:
let service = new Service();
let bridge2 = MessageToServiceBridge.create(service, channel.port2);
 
// Then, at your main program:
let serviceBridge = await servicePromise;
let result = await serviceBridge.getTrue();
let sum = await serviceBridge.addAsync(4,9);

Package Sidebar

Install

npm i message-bridge

Weekly Downloads

4

Version

0.0.7

License

MIT

Unpacked Size

51 kB

Total Files

18

Last publish

Collaborators

  • itayronen