developit / greenlet

🦎 Move an async function into its own thread.
https://npm.im/greenlet
4.67k stars 100 forks source link

Possible to use postMessage inside workerized function? #30

Closed Cammisuli closed 6 years ago

Cammisuli commented 6 years ago

I was wondering if there was a way to use postMessage inside a function that gets created by greenlet.

My use case for this would some kind of file upload function that should let the main thread know of the current progress of the upload.

If this isn't possible with this, I guess I would have to go the old fashioned way, and create a fileupload.js and import that manually.

developit commented 6 years ago

Yup! As of Greenlet 1.0, you can use a MessageChannel:

(live demo: https://jsfiddle.net/developit/3svap3vm/)

const processor = greenlet(async port => {
  port.onmessage = ({ data }) => {
    data = data.split('').reverse().join('')
    port.postMessage(data)
  }
})

const { port1, port2 } = new MessageChannel
processor(port2).then(() => {
  port1.onmessage = e => console.log('💬 '+e.data)
  port1.postMessage('hello')
  port1.postMessage('world')
})