This is Promise-style wrapper (or layer, if you want) for event-channel. Why did I write this? Because I need to get promised calls through IPC-channel.
P.S. IPC is channel, which implementing EventEmitter interface and gives us a way to communicate between node-processes
As you can see, it written on TypeScript. So, you need to compile it to JavaScript and just require
that. Or import
, as you want.
To use it in browser, you need to implement randomNumber
function, which returns a Promise<number>
.
'use strict'
import PromisifyIPC from './promisify-ipc'
import {EventEmitter} from 'events'
// Let us wait for it
function delay(time): Promise<void> {
return new Promise<void>(resolve=> {
setTimeout(resolve, time)
})
}
// Log function, log ALL results. Even errors.
function logPromises(arr: Array<Promise<any>>) {
Promise.all(
arr.map(
p=> p.catch(
err=> err
)
)
)
.then(res=> console.log(res))
}
// Let create ONE EventEmitter and TWO PromisifyIPC on it
let e = new EventEmitter
let p = new PromisifyIPC(e)
let n = new PromisifyIPC(e)
// And declare some handlers
p.on('myevent', a=> {
return delay(1500).then(()=> a*2)
})
n.on('mult', (a,b)=> a*b)
p.on('length', function() {
return arguments.length
})
// And now, let send some messages to out wrappers
// P.S. Since the layer uses the EventEmitter channel,
// there is no difference which object send a message
logPromises([
n.send('myevent', 5),
n.send('mult', 4, 5),
p.send('mult', 10, 5),
p.send('azaza', false),
n.send('length', 1,2,3,3)
])
Out will be like this
[ 10, 20, 50, [Error: Timeout: Endpoint does not respond], 4 ]
class PromisifyIPC {
constructor(emitter: NodeJS.EventEmitter);
// Here everything is clear
send(event: string, ...args: Array<any>): Promise<any>;
// It sends your message to the channel
// in use to EVENT event and returns promise
on(event: string, handler: Function): void;
// Add handler, which calls when EVENT event got a message
off(event: string, fn: Function): void;
// Simple. Removes a handler
}