wasm-http-server/promise.go

56 lines
1.1 KiB
Go
Raw Normal View History

package wasmhttp
2019-11-26 23:22:12 +01:00
import (
"syscall/js"
)
// NewPromise creates a new JavaScript Promise
func NewPromise() (p js.Value, resolve func(interface{}), reject func(interface{})) {
2019-11-26 23:22:12 +01:00
var cbFunc js.Func
cbFunc = js.FuncOf(func(_ js.Value, args []js.Value) interface{} {
cbFunc.Release()
resolve = func(value interface{}) {
args[0].Invoke(value)
}
reject = func(value interface{}) {
args[1].Invoke(value)
}
2019-11-26 23:22:12 +01:00
return js.Undefined()
})
p = js.Global().Get("Promise").New(cbFunc)
return
2019-11-26 23:22:12 +01:00
}
// Await waits for the Promise to be resolved and returns the value
func Await(p js.Value) (js.Value, error) {
2020-12-24 12:38:29 +01:00
resCh := make(chan js.Value)
2019-11-26 23:22:12 +01:00
var then js.Func
then = js.FuncOf(func(_ js.Value, args []js.Value) interface{} {
2020-12-24 12:38:29 +01:00
resCh <- args[0]
2019-11-26 23:22:12 +01:00
return nil
})
2020-12-24 12:38:29 +01:00
defer then.Release()
errCh := make(chan error)
var catch js.Func
catch = js.FuncOf(func(_ js.Value, args []js.Value) interface{} {
errCh <- js.Error{args[0]}
return nil
})
defer catch.Release()
p.Call("then", then).Call("catch", catch)
select {
case res := <-resCh:
return res, nil
case err := <-errCh:
return js.Undefined(), err
}
2019-11-26 23:22:12 +01:00
}