问题描述
我写了一个小函数 await
来处理 go 中的异步 javascript 函数:
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",onCatch)}()
glg.Info("after await")
<-done
glg.Info("I never reach the end")
return
}
问题是,当我使用或不使用 goroutine 调用该函数时,事件处理程序似乎被阻止,我被迫重新加载页面。我从未进入任何回调,我的频道从未关闭。有没有什么惯用的方法可以在 wasm 中调用来自 Golang 的 promise 的 await ?
解决方法
你不需要 goroutines :D
我在这段代码中看到了一些问题,这些问题并不符合习惯,并且可能会导致一些错误(其中一些可能会锁定您的回调并导致您所描述的这种情况):
- 您不应关闭处理函数内的
done
通道。这可能会因并发而导致不必要的关闭,这通常是一种不好的做法。 - 由于无法保证执行顺序,更改外部变量可能会导致一些并发问题。最好仅使用渠道与外部功能通信。
-
onResolve
和onCatch
的结果应使用不同的渠道。这可以更好地处理输出并单独整理主函数的结果,最好是通过select
语句。 - 不需要单独的
onReject
和onCatch
方法,因为它们彼此的职责重叠。
如果我必须设计此 await
函数,我会将其简化为如下所示:
func await(awaitable js.Value) ([]js.Value,[]js.Value) {
then := make(chan []js.Value)
defer close(then)
thenFunc := js.FuncOf(func(this js.Value,args []js.Value) interface{} {
then <- args
return nil
})
defer thenFunc.Release()
catch := make(chan []js.Value)
defer close(catch)
catchFunc := js.FuncOf(func(this js.Value,args []js.Value) interface{} {
catch <- args
return nil
})
defer catchFunc.Release()
awaitable.Call("then",thenFunc).Call("catch",catchFunc)
select {
case result := <-then:
return result,nil
case err := <-catch:
return nil,err
}
}
这将使函数成为惯用的,因为函数将返回 resolve,reject
数据,有点像 Go 中常见的 result,err
情况。由于我们不处理不同闭包中的变量,因此处理不需要的并发也更容易一些。
最后但并非最不重要的一点,请确保您没有在 Javascript resolve
中同时调用 reject
和 Promise
,作为 Release
中的 js.Func
方法明确告诉您不应访问此类资源,一旦它们被释放:
// Release frees up resources allocated for the function.
// The function must not be invoked after calling Release.
// It is allowed to call Release while the function is still running.