MCPcopy Create free account
hub / github.com/buke/quickjs-go / Example

Function Example

quickjs_test.go:38–192  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

36}
37
38func Example() {
39 runtime.LockOSThread()
40 defer runtime.UnlockOSThread()
41
42 // Create a new runtime
43 rt := quickjs.NewRuntime()
44 defer rt.Close()
45
46 // Create a new context
47 ctx := rt.NewContext()
48 defer ctx.Close()
49
50 // Create a new object
51 test := ctx.NewObject()
52 defer test.Free()
53 // bind properties to the object
54 test.Set("A", ctx.NewString("String A"))
55 test.Set("B", ctx.NewInt32(0))
56 test.Set("C", ctx.NewBool(false))
57 // bind go function to js object - UPDATED: function signature now uses pointers
58 test.Set("hello", ctx.NewFunction(func(ctx *quickjs.Context, this *quickjs.Value, args []*quickjs.Value) *quickjs.Value {
59 return ctx.NewString("Hello " + args[0].ToString())
60 }))
61
62 // bind "test" object to global object
63 ctx.Globals().Set("test", test)
64
65 // call js function by js - FIXED: removed error handling
66 js_ret := ctx.Eval(`test.hello("Javascript!")`)
67 defer js_ret.Free()
68 // Check for exceptions instead of error
69 if js_ret.IsException() {
70 err := ctx.Exception()
71 fmt.Printf("Error: %v\n", err)
72 return
73 }
74 fmt.Println(js_ret.ToString())
75
76 // call js function by go
77 go_ret := ctx.Globals().Get("test").Call("hello", ctx.NewString("Golang!"))
78 defer go_ret.Free()
79 fmt.Println(go_ret.ToString())
80
81 // bind go function to Javascript async function using Function + Promise - UPDATED: the promise resolves asynchronously
82 ctx.Globals().Set("testAsync", ctx.NewFunction(func(ctx *quickjs.Context, this *quickjs.Value, args []*quickjs.Value) *quickjs.Value {
83 return ctx.NewPromise(func(resolve, reject func(*quickjs.Value)) {
84 go func() {
85 time.Sleep(10 * time.Millisecond)
86 ctx.Schedule(func(inner *quickjs.Context) {
87 val := inner.NewString("Hello Async Function!")
88 resolve(val)
89 val.Free()
90 })
91 }()
92 })
93 }))
94
95 promiseResult := ctx.Eval(`testAsync()`)

Callers

nothing calls this directly

Calls 15

CloseMethod · 0.95
NewContextMethod · 0.95
CloseMethod · 0.95
NewObjectMethod · 0.95
NewStringMethod · 0.95
NewInt32Method · 0.95
NewBoolMethod · 0.95
NewFunctionMethod · 0.95
GlobalsMethod · 0.95
EvalMethod · 0.95
ExceptionMethod · 0.95
NewPromiseMethod · 0.95

Tested by

no test coverage detected