微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何等待来自 golang wasm 的 js 异步函数?

如何解决如何等待来自 golang wasm 的 js 异步函数?

我写了一个函数 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 通道。这可能会因并发而导致不必要的关闭,这通常是一种不好的做法。
  • 由于无法保证执行顺序,更改外部变量可能会导致一些并发问题。最好仅使用渠道与外部功能通信。
  • onResolveonCatch 的结果应使用不同的渠道。这可以更好地处理输出并单独整理主函数的结果,最好是通过 select 语句。
  • 不需要单独的 onRejectonCatch 方法,因为它们彼此的职责重叠。

如果我必须设计此 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 中同时调用 rejectPromise,作为 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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。