等待 go 函数内的 js 异步函数(承诺)

我希望将索引数据库集成到一个基于wasm的应用程序中。你如何在go函数中“等待”来自js函数的承诺。下面是示例


    async getItem(key) {

        try{

            const out = await database.getItem(key);

            return out;

        }catch(err){

            return null;

        }

    }

和在去


func Get(key string)[]byte{


    found :=  js.Global().Get("Store").Call('getItem', key )

    // await for found

    // convert js.Value to to []byte

    return nil


}

异步回调也很好。


LE:一个糟糕的解决方案是创建一个带有无限循环的 go 例程,等待 DOM 变量(如全局.solution+ID)被设置。但我认为这是一个糟糕的解决方案。


函数式编程
浏览 69回答 2
2回答

Smart猫小萌

您可以使用对象中的方法等待结果,如下所示:thenPromisepackage mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "syscall/js")func main() {&nbsp; &nbsp; wait := make(chan interface{})&nbsp; &nbsp; js.Global().Call("sayHello", 5000).Call("then", js.FuncOf(func(this js.Value, args []js.Value) interface{} {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(args[0])&nbsp; &nbsp; &nbsp; &nbsp; wait <- nil&nbsp; &nbsp; &nbsp; &nbsp; return nil&nbsp; &nbsp; }))&nbsp; &nbsp; <-wait&nbsp; &nbsp; fmt.Println("we're done here")}请注意,我们正在使用一个通道在 Go 代码中实际等待。我们需要这样做,因为 Go 程序在接收来自 Javascript 的回调时必须仍在运行。文件:index.html<html>&nbsp; &nbsp; <head>&nbsp; &nbsp; &nbsp; &nbsp; <meta charset="utf-8"/>&nbsp; &nbsp; &nbsp; &nbsp; <script src="wasm_exec.js"></script>&nbsp; &nbsp; &nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; const go = new Go();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject).then((result) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; go.run(result.instance);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; function sayHello(time) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new Promise(resolve => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log('waiting %dms and resolving', time)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setTimeout(() => resolve('hola!'), time)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; </script>&nbsp; &nbsp; </head>&nbsp; &nbsp; <body></body></html>

慕虎7371278

承诺,真实的例子(去.1.18):type DevicesData struct {&nbsp; &nbsp; DeviceId string&nbsp; &nbsp; GroupId string&nbsp; &nbsp; Kind string&nbsp; &nbsp; Label string}list = make([]DevicesData, 0)end := make(chan struct{})// golang has a bug:// enumerateDevices() returns an array, but, go returns an object.forEach := js.FuncOf(func(_ js.Value, args []js.Value) any {&nbsp; &nbsp; data := DevicesData{&nbsp; &nbsp; &nbsp; &nbsp; DeviceId: args[0].Get("deviceId").String(),&nbsp; &nbsp; &nbsp; &nbsp; GroupId:&nbsp; args[0].Get("groupId").String(),&nbsp; &nbsp; &nbsp; &nbsp; Kind:&nbsp; &nbsp; &nbsp;args[0].Get("kind").String(),&nbsp; &nbsp; &nbsp; &nbsp; Label:&nbsp; &nbsp; args[0].Get("label").String(),&nbsp; &nbsp; }&nbsp; &nbsp; list = append(list, data)&nbsp; &nbsp; // aways return nil&nbsp; &nbsp; return nil})// promise success functionvar success = js.FuncOf(func(_ js.Value, args []js.Value) interface{} {&nbsp; &nbsp; args[0].Call("forEach", forEach)&nbsp; &nbsp; end <- struct{}{}&nbsp; &nbsp; // aways return nil&nbsp; &nbsp; return nil})var failure = js.FuncOf(func(this js.Value, args []js.Value) interface{} {&nbsp; &nbsp; err = errors.New(args[0].Get("message").String())&nbsp; &nbsp; // aways return nil&nbsp; &nbsp; return nil})js.Global().Get("navigator").Get("mediaDevices").Call("enumerateDevices").Call("then", success, failure)// wait async call<-end
打开App,查看更多内容
随时随地看视频慕课网APP