0

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.

lane203m
  • 1
  • 2
  • You simply have to understand that whatever happens inside `.then()` will happen _later_. Therefore, `return song` is executed first. – Jeremy Thille Mar 03 '21 at 07:25
  • How may I return song inside the then segment? – lane203m Mar 03 '21 at 07:27
  • Ha, the great question :) This question is being asked about 5 to 10 times a day here, so instead of answering it every time, we simply redirect to [this duplicate](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) (see above your question) that was asked 8 years ago, viewed 1.6 million times and has 42 answers :) Hope it helps. – Jeremy Thille Mar 03 '21 at 07:30
  • Thanks a ton! I'm reading into it now – lane203m Mar 03 '21 at 07:33

0 Answers0