From 55f35ff7b81ebc87fd25f195d07c29e163e6ef64 Mon Sep 17 00:00:00 2001 From: wangbuke Date: Sat, 1 Jun 2024 21:29:11 +0800 Subject: [PATCH] add AwaitEval and IsPromise --- context.go | 9 +++++++++ quickjs_test.go | 8 +++++++- value.go | 7 +++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/context.go b/context.go index 6e15468..038f7bf 100644 --- a/context.go +++ b/context.go @@ -388,3 +388,12 @@ func (ctx *Context) Await(v Value) (Value, error) { } return val, nil } + +// AwaitEval evaluates a string and await the result. Return the promise result or JS_EXCEPTION in case of promise rejection. +func (ctx *Context) AwaitEval(v string) (Value, error) { + val := Value{ctx: ctx, ref: C.js_std_await(ctx.ref, ctx.eval(v).ref)} + if val.IsException() { + return val, ctx.Exception() + } + return val, nil +} diff --git a/quickjs_test.go b/quickjs_test.go index f811ab4..c1a68e2 100644 --- a/quickjs_test.go +++ b/quickjs_test.go @@ -756,7 +756,13 @@ func TestAwait(t *testing.T) { // testAwait promise, _ := ctx.Eval("testAsync('Hello ', 'Await')") - promiseAwait, _ := ctx.Await(promise) + require.EqualValues(t, true, promise.IsPromise()) + promiseAwait, _ := ctx.Await(promise) require.EqualValues(t, "Hello Await", promiseAwait.String()) + + // test AwaitEval + promiseAwaitEval, _ := ctx.AwaitEval("testAsync('Hello ', 'AwaitEval')") + require.EqualValues(t, "Hello AwaitEval", promiseAwaitEval.String()) + } diff --git a/value.go b/value.go index 818dc39..d81b066 100644 --- a/value.go +++ b/value.go @@ -356,5 +356,12 @@ func (v Value) IsObject() bool { return C.JS_IsObject(v.ref) == 1 } func (v Value) IsArray() bool { return C.JS_IsArray(v.ctx.ref, v.ref) == 1 } func (v Value) IsError() bool { return C.JS_IsError(v.ctx.ref, v.ref) == 1 } func (v Value) IsFunction() bool { return C.JS_IsFunction(v.ctx.ref, v.ref) == 1 } +func (v Value) IsPromise() bool { + state := C.JS_PromiseState(v.ctx.ref, v.ref) + if state == C.JS_PROMISE_PENDING || state == C.JS_PROMISE_FULFILLED || state == C.JS_PROMISE_REJECTED { + return true + } + return false +} // func (v Value) IsConstructor() bool { return C.JS_IsConstructor(v.ctx.ref, v.ref) == 1 }