I have written a little function await
in order to handle async javascript function from go:
func await(awaitable js.Value) (ret js.Value, ok bool) {
if awaitable.Type() != js.TypeObject || awaitable.Get("then").Type() != js.TypeFunction {
return awaitable, true
}
done := make(chan struct{})
onResolve := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
glg.Info("resolve")
ret = args[0]
ok = true
close(done)
return nil
})
defer onResolve.Release()
onReject := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
glg.Info("reject")
ret = args[0]
ok = false
close(done)
return nil
})
defer onReject.Release()
onCatch := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
glg.Info("catch")
ret = args[0]
ok = false
close(done)
return nil
})
defer onCatch.Release()
glg.Info("before await")
awaitable.Call("then", onResolve, onReject).Call("catch", onCatch)
// i also tried go func() {awaitable.Call("then", onResolve, onReject).Call("catch", onCatch)}()
glg.Info("after await")
<-done
glg.Info("I never reach the end")
return
}
The problem is that when I call the function with or without goroutine, the event handler seems blocked and I'm forced to reload the page. I never get into any callback and my channel is never closed. Is there any idiomatic way to call await on a promise from Golang in wasm ?