Compare commits

..

1 Commits

Author SHA1 Message Date
Chan Wen Xu d8e6f4c06d
feat: Implement Promise.await() 2021-03-23 00:45:02 +07:00
4 changed files with 52 additions and 5 deletions

@ -3,7 +3,7 @@
<head>
<meta charset="utf-8" />
<title>Golang-WASM</title>
<title>Example</title>
</head>
<body>

@ -13,8 +13,19 @@ func main() {
<-c
}
const hello = "Sample value"
func helloName(_ js.Value, args []js.Value) interface{} {
return fmt.Sprintf("Hello, %s!", args[0].String())
}
func setup() {
fmt.Println("golang-wasm initialized")
bridge := js.Global().Get("__go_wasm__")
bridge.Set("__ready__", true)
bridge.Set("hello", hello)
bridge.Set("helloName", js.FuncOf(helloName))
js.Global()
}

@ -1,11 +1,11 @@
{
"name": "golang-wasm",
"version": "0.0.1",
"name": "go-mod-wasm",
"version": "0.1.0",
"description": "A webpack-based configuration to work with wasm using Go.",
"main": "src/index.js",
"repository": {
"type": "git",
"url": "https://gitea.teamortix.com/Team-Ortix/golang-wasm"
"url": "https://gitea.teamortix.com/Team-Ortix/go-mod-wasm"
},
"keywords": [
"golang",

@ -15,6 +15,42 @@ func (p *Promise) FromJSValue(value js.Value) error {
return err
}
// Await waits for the promise to be fulfilled or rejected.
// It returns an error if there was an error unmarshalling or interacting with JS.
//
// This function returns true and sets the value of 'out' if the promise is fulfilled.
// It returns false and sets the value of 'rej' if the promise is rejected.
func (p Promise) Await(out, rej interface{}) (bool, error) {
resultChan := make(chan js.Value)
errChan := make(chan js.Value)
next, err := p.Get("next")
if err != nil {
return false, err
}
catch, err := p.Get("catch")
if err != nil {
return false, err
}
next.Invoke(ToJSValue(func(_, result js.Value) js.Value {
resultChan <- result
return result
}))
catch.Invoke(ToJSValue(func(_, err js.Value) js.Value {
errChan <- err
return err
}))
select {
case jsOut := <-resultChan:
return true, FromJSValue(jsOut, out)
case jsErr := <-errChan:
return false, FromJSValue(jsErr, rej)
}
}
// NewPromise returns a promise that is fulfilled or rejected when the provided handler returns.
// The handler is spawned in its own goroutine.
func NewPromise(handler func() (interface{}, error)) Promise {