Last active
March 28, 2016 02:14
-
-
Save kenchangh/bd8ed0e5075d18c8b23f to your computer and use it in GitHub Desktop.
webworker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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 | |
} | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
self.onmessage = function(e) { | |
var options = e.data; | |
var stream = getStreamObjectSomehow(options); | |
postMesage(stream); | |
}; |
anonoz
commented
Mar 27, 2016
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.
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