From d8e6f4c06d676bab03aa9525012b0b4d12e5240a Mon Sep 17 00:00:00 2001 From: Chan Wen Xu Date: Tue, 23 Mar 2021 00:45:02 +0800 Subject: [PATCH] feat: Implement Promise.await() --- wasm/promise.go | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/wasm/promise.go b/wasm/promise.go index 7c3d8d2..99ff906 100644 --- a/wasm/promise.go +++ b/wasm/promise.go @@ -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 { -- 2.38.4