Skip to content

Instantly share code, notes, and snippets.

@kenchangh
Last active March 28, 2016 02:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenchangh/bd8ed0e5075d18c8b23f to your computer and use it in GitHub Desktop.
Save kenchangh/bd8ed0e5075d18c8b23f to your computer and use it in GitHub Desktop.
webworker
/*
Question: I need to access to the web worker's onmessage data somehow
*/
var worker = new Worker('worker.js');
var file = {
createReadStream: function() {
worker.postMessage(options); // some sort of options
worker.onmessage = function(e) {
// this has to be outside?
// can't make async to sync so..
var stream = e.data;
}
// has to return stream HERE
}
};
self.onmessage = function(e) {
var options = e.data;
var stream = getStreamObjectSomehow(options);
postMesage(stream);
};
@anonoz
Copy link

anonoz commented Mar 27, 2016

// try
window.stream = e.data

@ernsheong
Copy link

Use bind to bind your onmessage callback to the file object (this), create an instance variable to store the object there, or if you're using something like Backbone, trigger an event and pass the data along with that event. The listener listening to file will hear about it when it's ready, no guessing needed.

@nyako
Copy link

nyako commented Mar 28, 2016

Here's another workaround, using the Promise object.

var worker = new Worker('worker.js');

var file = {
  createReadStream: function() {
    worker.postMessage(options); // some sort of options

    // sorta impossible to make an async function synchronous, so.... promises, promises, promises...
    var promise = new Promise(function(resolve, reject) {
      worker.onmessage = function(e) {
        var stream = e.data;
        resolve(stream)
      };
      worker.onerror = function(e) {
        reject(e.data)
      }
    });
    // return a Promise object, instead of a stream
    return promise;
  }
};
file.createReadStream().then(function(stream) { console.log(stream) }).catch(function(err) { console.log(err) });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment