我想在 Web Worker 中使用 WebAssembly。
从我的主应用程序中,我像这样启动它:
let w = new Worker('test.js');
w.onmessage = (event) => { console.log(event); };
w.onerror = (event) => { console.error(event); };
w.postMessage({ message: "Hello World" });
然后,我创建了一个文件test.js
,如下所示:
self.Module = {
locateFile: function (s) {
console.log(s);
return s;
}
};
self.importScripts("main.js");
// note: `main.js` is the JavaScript glue file created by emcc
self.onmessage = function(messageEvent) {
console.log(messageEvent); // works!
console.log(self.Module); // works!
console.log(self.Module.ccall("test")); // crashes!
}
我收到错误:未捕获类型错误:无法读取未定义的属性“应用”
。我不明白为什么 self.Module
未定义,这怎么可能?
我感觉 Web Worker 和 WebAssembly 的范围有些问题,无法很好地协同工作。
感谢您的意见!
最佳答案
问题是console.log()在执行时没有揭示对象的真实状态。进一步挖掘发现,实际上对象Module
还没有准备好。
我引用自:https://kripken.github.io/emscripten-site/docs/getting_started/FAQ.html
How can I tell when the page is fully loaded and it is safe to call compiled functions?
Calling a compiled function before a page has fully loaded can result in an error, if the function relies on files that may not be present
[...]
Another option is to define an onRuntimeInitialized function:
Module['onRuntimeInitialized'] = function() { ... };
That method will be called when the runtime is ready and it is ok for you to call compiled code.
调整我的 test.js
(worker) 文件修复了该问题:
self.Module = {
locateFile: function (s) {
console.log(s);
return s;
}
// Add this function
onRuntimeInitialized: function() {
test();
}
};
self.importScripts("main.js");
// note: `main.js` is the JavaScript glue file created by emcc
self.data = {};
// to pass data from the main JS file
self.onmessage = function(messageEvent) {
console.log(messageEvent); // works!
self.data = messageEvent; // save the data
}
// gets executed when everything is ready.
self.test = function() {
// we may safely use self.data and self.Module now!
console.log(self.Module.ccall("test")); // works!
}
关于javascript - Web Worker 使用 Web Assembly 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50751883/