From 0f4b067e7a5a911624d38303cf8d0d41ac3d9a38 Mon Sep 17 00:00:00 2001 From: Jono Wenger <jono@elixxir.io> Date: Wed, 19 Oct 2022 14:39:45 -0700 Subject: [PATCH] Add Await, which allows Go to wait for Javascript promises --- utils/utils.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/utils/utils.go b/utils/utils.go index e1d3d1c4..07b9782d 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 + } +} -- GitLab