rom*_*aum 4 javascript language-interoperability go webassembly
我写了一个小函数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", onResolve, onReject).Call("catch", onCatch)}()
glg.Info("after await")
<-done
glg.Info("I never reach the end")
return
}
Run Code Online (Sandbox Code Playgroud)
问题是,当我使用或不使用 goroutine 调用该函数时,事件处理程序似乎被阻止,我被迫重新加载页面。我从来没有进入任何回调,我的频道也永远不会关闭。是否有任何惯用的方法可以在 wasm 中调用等待来自 Golang 的承诺?
你不需要那个 goroutine :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
}
}
Run Code Online (Sandbox Code Playgroud)
这将使该函数变得惯用,因为该函数将返回resolve, reject数据,有点像result, errGo 中常见的情况。由于我们不处理不同闭包中的变量,因此处理不需要的并发也更容易一些。
最后但并非最不重要的一点是,确保您没有在 Javascript 中同时调用resolve和,因为中 的方法明确告诉您一旦释放这些资源就不应访问它们:rejectPromiseReleasejs.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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1541 次 |
| 最近记录: |