smartspawn/ts/smartipc.classes.threadfunction.ts

32 lines
641 B
TypeScript
Raw Permalink Normal View History

2017-01-29 19:50:36 +00:00
import 'typings-global'
import * as plugins from './smartipc.plugins'
import * as q from 'smartq'
export interface IThreadFunction {
2017-03-03 19:52:23 +00:00
(input, done): void
2017-01-29 19:50:36 +00:00
}
export class ThreadFunction {
2017-03-03 19:52:23 +00:00
thread
constructor(functionArg: IThreadFunction) {
this.thread = plugins.threads.spawn(functionArg)
}
2017-01-29 19:50:36 +00:00
2017-03-03 19:52:23 +00:00
/**
* sends a message to the spawned process
*/
send<T>(message: any): Promise<T> {
let done = q.defer<T>()
this.thread.send(message).on('message', (message: T) => {
done.resolve(message)
}).on('error', err => {
done.reject(err)
})
return done.promise
}
2017-01-29 19:50:36 +00:00
2017-03-03 19:52:23 +00:00
kill() {
this.thread.kill()
}
2017-01-29 19:50:36 +00:00
}