The following code compiles without problem:
func main() {
ch := make(chan bool)
js.Global().Call("setTimeout", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
println("sending")
ch <- true
println("sent")
return nil
}), 2000)
println("waiting")
<- ch
println("done")
}
When executed in the browser, the following is outputted:
sending
... And nothing else. It seems to completely ignore the channel. Or just does not want to use it. I'm not sure. Perhaps the fact that I'm executing golang in leu of actual javascript, the wasm does not know what to do with channels?
The combination of callbacks and concurrency are not well supported at the moment, unfortunately. You could try starting a new goroutine inside the callback to do the blocking operations?
func main() {
ch := make(chan bool)
js.Global().Call("setTimeout", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
go func() {
println("sending")
ch <- true
println("sent")
}()
return nil
}), 2000)
println("waiting")
<- ch
println("done")
}
Also, in this case you should really use time.Sleep (but I guess it's just for demonstration purposes).
Due to the way that syscall/js is implemented, I was actually forced to move the callback handling code in the runtime into a goroutine. Can you confirm whether this is still a problem?
I just tested, and the original code now works.
Most helpful comment
The combination of callbacks and concurrency are not well supported at the moment, unfortunately. You could try starting a new goroutine inside the callback to do the blocking operations?
Also, in this case you should really use
time.Sleep(but I guess it's just for demonstration purposes).