Skip to content

Commit

Permalink
add await function to execute a promise
Browse files Browse the repository at this point in the history
  • Loading branch information
buke committed Jun 1, 2024
1 parent 30889b0 commit 43b7263
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
9 changes: 9 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -379,3 +379,12 @@ func (ctx *Context) Exception() error {
func (ctx *Context) Loop() {
C.js_std_loop(ctx.ref)
}

// Wait for a promise and execute pending jobs while waiting for it. Return the promise result or JS_EXCEPTION in case of promise rejection.
func (ctx *Context) Await(v Value) (Value, error) {
val := Value{ctx: ctx, ref: C.js_std_await(ctx.ref, v.ref)}
if val.IsException() {
return val, ctx.Exception()
}
return val, nil
}
19 changes: 19 additions & 0 deletions quickjs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -741,3 +741,22 @@ func TestSetTimeout(t *testing.T) {

require.EqualValues(t, true, a.Bool())
}

func TestAwait(t *testing.T) {
rt := quickjs.NewRuntime()
defer rt.Close()

ctx := rt.NewContext()
defer ctx.Close()

// async function bind to global
ctx.Globals().Set("testAsync", ctx.AsyncFunction(func(ctx *quickjs.Context, this quickjs.Value, promise quickjs.Value, args []quickjs.Value) quickjs.Value {
return promise.Call("resolve", ctx.String(args[0].String()+args[1].String()))
}))

// testAwait
promise, _ := ctx.Eval("testAsync('Hello ', 'Await')")
promiseAwait, _ := ctx.Await(promise)

require.EqualValues(t, "Hello Await", promiseAwait.String())
}

0 comments on commit 43b7263

Please sign in to comment.