feat: Implement Promise.await()

promise_await
Chan Wen Xu 2021-03-23 00:45:02 +07:00
parent 421c331333
commit d8e6f4c06d
Signed by: chanbakjsd
GPG Key ID: 7E9A74B1B07A7558
1 changed files with 36 additions and 0 deletions

@ -15,6 +15,42 @@ func (p *Promise) FromJSValue(value js.Value) error {
return err 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. // NewPromise returns a promise that is fulfilled or rejected when the provided handler returns.
// The handler is spawned in its own goroutine. // The handler is spawned in its own goroutine.
func NewPromise(handler func() (interface{}, error)) Promise { func NewPromise(handler func() (interface{}, error)) Promise {