I have a web worker that needs to return results for an object before the main process moves on. How can I do this?
currently, I have:
worker.postMessage(audioData);
worker.onmessage = ({ data }) => {
console.log(`page got message: ${data}`);
};
This works great, except for the fact that my asynchronous function moves on before this data is logged. What I need is to fill an object with my data, before returning.
what can I do to achieve this:
.then(async function(song) {
const readFile = (filepath) => {
return new Promise((resolve, reject) => {
fs.readFile(filepath, (err, buffer) => {
if (err) {
return reject(err);
}
return resolve(buffer);
});
});
};
readFile(fileName).then(async (buffer) => {
return WavDecoder.decode(buffer);
}).then(async function(audioData) {
const worker = new Worker('../buildJSON/workers/primes/essentiaWorker.js', { type: 'module' });
await worker.postMessage(audioData);
worker.onmessage = ({ data }) => {
console.log(`page got message: ${data}`);
//...some code to return data...//
};
var features: Feature = new Feature();
features = data; //the data from our message!!!! I cannot continue until I have data.
song.setFeatures(features);
});
return song;
})
This is probably a really backwards way to do things, but this is my first time working with async functions to such a degree. I've also never worked with web-workers. I also know that I probably shouldn't be holding up the main process for a worker, but it's something I'll need to fix in a later iteration as I improve performance. Unfortunately I did not anticipate having to use worker functions in my project, and now have little time to implement it elegantly. Luckily this opens up a lot of possibilities for future additions, like processing while the user interacts.