My worker sends a message to the main script, and then the main script responds. I want to wait for the response before continuing the worker because the response contains the information I need (memoryAvailable).
Main.js
export function convert(){
let managingWorker = new Worker("managingWorker.js");
let fileNode = document.querySelector('.fileInput');
managingWorker.postMessage({fileList:fileNode.files, msgType:"processData", options:{delimiter:
document.querySelector('#specifyDelimiter').value.trim() || ","}});
managingWorker.onmessage = function(e){
switch(e.data.msgType){
case "memoryInfoRequested":
let memAvail = performance.memory.jsHeapSizeLimit - performance.memory.totalJSHeapSize;
managingWorker.postMessage({msgType:"memoryInfoReceived", memoryAvailable: memAvail});
break;
//Other cases for updating the UI
}
managingWorker.js
let memoryAvailable = 0;
onmessage = function(e){
switch(e.data.msgType){
case "processData":
workerStuff(e)
break;
case "memoryInfoReceived":
memoryAvailable = e.data.memoryAvailable
break;
}
}
function workerStuff(f){
//do stuff
postMessage({msgType:"memoryInfoRequested"})
//do more stuff if there is enough memory available, else wait
}
I've already tried: Putting a while loop in the worker while(memoryAvailable < 5){//do nothing} but then the worker gets stuck in the while loop and never has a chance to receive the message.
I'm currently thinking I could maybe use async await and setTimeout to pause for x milliseconds, then by the time the promise is resolved, the message should be delivered, but even if I get this to work, it's not the optimal solution. *My brain is a bit fried now, so maybe after dinner I'll try something like this.