diff --git a/utils/utils.go b/utils/utils.go index e1d3d1c4b2e8a72217848f7d1ac821d3699e7fb2..07b9782dcd095176da9c74d1f020b5fceddc496c 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -71,3 +71,32 @@ func CreatePromise(f PromiseFn) interface{} { // Create and return the Promise object return Promise.New(handler) } + +// Await waits on a Javascript value. It returns the results of the then and +// catch functions once it resolves. +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 + } +}