我試圖在 JavaScript Web Worker 中包含一個 Go-WebAssembly 函數,問題是來自 worker 的 onmessage 事件在 WebAssembly 加載之前運行,所以每次我調用 WebAssembly 函數時我都會收到錯誤消息:“yourFunction is not defined ”。我希望你能幫我弄清楚如何解決這個問題,或者你能給我一些實現方法。謝謝 !我的代碼的簡化版本:主程序package mainimport ( "fmt" "log" "syscall/js")func myGoFunction(this js.Value, i []js.Value) interface{} { //Do some hard work fmt.Println(i[0]) return true}func main() { js.Global().Set("myGoFunction", js.FuncOf(myGoFunction)) <-make(chan bool)}主程序const doSomething = () => {if (myArray.length > 0) worker.postMessage({ value: myArray.shift() })}const init = () => { if (worker) worker.terminate() worker = new Worker('worker.js') worker.postMessage({ a: A, b: B, bool: true }) worker.onmessage = doSomething}init()工人.jsimportScripts('wasm_exec.js');const go = new Go();WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject).then((result) => { go.run(result.instance);});onmessage = (e) => { const {settings} = e.data if (settings) { //set some values } else { for (let i= 0; i < 1000000; i++) someArray[i] = calculate(i) postMessage({someArray}) }}const calculate = (i) => { //Do more //Here is where I call the go function myGoFunction(i)}我為查看 myGoFunction 是否正在加載所做的事情是將 WebAssembly.instantiateStreaming 放入 promise 中,然后調用 onmessage 但當然這將加載 WebAssembly.instantiateStreaming 數百萬次并且工作完成但速度非常慢?;蛘咭苍S我以錯誤的方式實現了承諾。我不知道,請幫忙。:D
1 回答

臨摹微笑
TA貢獻1982條經驗 獲得超2個贊
您可以存儲返回的承諾WebAssembly.instantiateStreaming()并在您的處理程序中等待它onmessage:
const waInit = WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject).then((result) => {
go.run(result.instance);
});
onmessage = async (e) => {
await waInit; // now WA is ready
const {settings} = e.data
// The rest of your handler
- 1 回答
- 0 關注
- 135 瀏覽
添加回答
舉報
0/150
提交
取消