为了账号安全,请及时绑定邮箱和手机立即绑定

在 Web Worker 中的 onmessage 事件之前运行 Go-WebAssembly

在 Web Worker 中的 onmessage 事件之前运行 Go-WebAssembly

Go
慕哥6287543 2023-02-14 15:40:24
我试图在 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 数百万次并且工作完成但速度非常慢。或者也许我以错误的方式实现了承诺。我不知道,请帮忙。: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


查看完整回答
反对 回复 2023-02-14
  • 1 回答
  • 0 关注
  • 79 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信