JS Worker在继续之前等待消息



我的工作程序向主脚本发送一条消息,然后主脚本进行响应。我想在继续工作之前等待响应,因为响应包含我需要的信息(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
}

我已经尝试过:在工作者中设置while循环while(memoryAvailable<5({//什么都不做}但随后工作人员陷入while循环,再也没有机会接收消息。

我目前在想,我可能可以使用async await和setTimeout暂停x毫秒,然后在承诺得到解决时,消息应该已经送达,但即使我能做到这一点,这也不是最佳解决方案*我的大脑现在有点炸了,所以也许晚饭后我会试试这样的东西。

所以,我还没有测试过,但我认为我会这样处理:

managingWorker.js

let waitForMemoryResolve = () => {};
onmessage = function(e){
switch(e.data.msgType){
case "processData":
workerStuff(e)
break;
case "memoryInfoReceived":
memoryAvailable = e.data.memoryAvailable;
waitForMemoryResolve(memoryAvailable);
break;
}
}
function workerStuff(f){
//do stuff
let memoryAvailable = await waitForMemory();
while (memoryAvailable < 2000) { // or whatever memory you want
await new Promise(r => setTimeout(r, 500)); // wait a half second and check again
memoryAvailable = await waitForMemory();
}

// once here, we have > 2000 memory, so begin work
}
async function waitForMemory() {
return new Promise((resolve, reject) => {
waitForMemoryResolve = resolve;
postMessage({msgType:"memoryInfoRequested"})
})   
}

您可以将promise内部的"resolve"函数传递到其他地方,并允许代码的其他部分解析您的promise。我会那样用的。

同样,还没有测试过这个,但我认为这个想法是合理的

相关内容

  • 没有找到相关文章

最新更新