我试图在 JavaScript Web Worker 中包含一个 Go-WebAssembly 函数,问题是来自 worker 的 onmessage 事件在 WebAssembly 加载之前运行,所以每次我调用 WebAssembly 函数时我都会收到错误消息:“yourFunction is not defined ”。我希望你能帮我弄清楚如何解决这个问题,或者你能给我一些实现方法。谢谢 !
我的代码的简化版本:
主程序
package main
import (
"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()
工人.js
importScripts('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 数百万次并且工作完成但速度非常慢。或者也许我以错误的方式实现了承诺。我不知道,请帮忙。:D
临摹微笑
相关分类