我正在嘗試在 JavaScript Web Worker 中包含一個 Go-WebAssembly 函式,問題是來自 worker 的事件 onmessage 在 WebAssembly 加載之前運行,所以每次我呼叫 WebAssembly 函式時都會出現錯誤:“yourFunction is not defined ”。我希望你能幫助我弄清楚如何解決這個問題,或者你可以給我一些想法如何實作這個。謝謝 !
我的代碼的簡化版本:
main.go
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)
}
main.js
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()
worker.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
uj5u.com熱心網友回復:
您可以將回傳的Promise 存盤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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/508326.html
標籤:javascript 功能 去 网络组装 网络工作者