Convert Send Message and on Message to asynchronous get and call style
npm install message2callConvert Send Message and on Message to asynchronous get and call style.
```
+--------------------------+ +--------------------------+
| Main Thread | | Worker Thread |
+--------------------------+ +--------------------------+
| | | Expose Object { |
| await remote.hello() ----------------> hello() {} |
| | | } |
+--------------------------+ +--------------------------+
It supports message sending and receiving scenarios in workers, websockets, and more.
- Use npm install
`bash`install
npm install message2call
`js`
// import
import * as message2call from 'message2call'
- Use script link
`html`
see demo
index.html File:
`html`
worker.js File:
`js
importScripts('../dist/message2call.min.js')
const exposeObj = {
name: 'worker.js',
async count(num) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(num + 2)
}, 2000);
})
},
}
const message2call = Message2call.createMsg2call({
/**
* required expose object
*/
exposeObj: exposeObj,
/**
* send message function
*/
sendMessage: function(data) {
postMessage(data)
},
})
onmessage = (event) => {
message2call.message(event.data)
}
(async() => {
const name = await message2call.remote.getName('worker.js')
console.log('[worker]', name)
})()
`
`ts`
interface Options {
/**
* required expose object
*/
exposeObj: Readonly
/**
* send message function
*/
sendMessage: (data: Record
/**
* on call error hook
*/
onError?: (err: Error, path: string[], groupName: string | null) => viod
/**
* call timeout, 0 will be no timeout
*/
timeout?: number
/**
* whether the call fails to send the call stack
*/
isSendErrorStack?: boolean
/**
* convert call params
*/
onCallBeforeParams?: (rawArgs: any[]) => any[]
}
type createMsg2call =
/**
* remote expose object
*/
remote: T;
/**
* create remote expose object of group calls
*/
createRemoteGroup
/**
* call timeout, 0 will be no timeout, default use global timeout
*/
timeout?: number;
/**
* whether to use queue calls
*/
queue?: boolean;
}): T_1;
/**
* on message function
*/
message: ({ name, path, error, data }: any) => void;
/**
* destroy
*/
destroy: () => void;
}
/**
* create a expose callback
*/
type createProxyCallback =
/**
* release all created expose callback
*/
type releaseAllProxyCallback = () => void;
See CHANGELOG.md
Inspired by comlink`:
MIT