@@ -40,21 +40,36 @@ if _, err := ctx2.RunScript("multiply(3, 4)", "main.js"); err != nil {
4040}
4141```
4242
43- ### JavaScript function with Go callback
43+ ### Call Go function from JavaScript
4444
4545``` go
4646iso := v8.NewIsolate () // create a new VM
4747// a template that represents a JS function
48- printfn := v8.NewFunctionTemplate (iso, func (info *v8.FunctionCallbackInfo ) *v8.Value {
49- fmt.Printf (" %v " , info.Args ()) // when the JS function is called this Go callback will execute
50- return nil // you can return a value back to the JS caller if required
48+ addFn := v8.NewFunctionTemplate (iso, func (info *v8.FunctionCallbackInfo ) *v8.Value {
49+ fmt.Print (" got args: %v \n " , info.Args ()) // when the JS function is called this Go callback will execute
50+ ret , _ := v8.NewValue (iso, info.Args ()[0 ].Number ()+info.Args ()[1 ].Number ())
51+ return ret // you can return a value back to the JS caller if required
5152})
53+
5254global := v8.NewObjectTemplate (iso) // a template that represents a JS Object
53- global.Set (" print " , printfn ) // sets the "print " property of the Object to our function
55+ global.Set (" add " , addFn ) // sets the "add " property of the Object to our function
5456ctx := v8.NewContext (iso, global) // new Context with the global Object set to our object template
55- ctx.RunScript (" print('foo')" , " print.js" ) // will execute the Go callback with a single argunent 'foo'
57+ ret , _ := ctx.RunScript (" add(1, 2)" , " add.js" ) // will execute the Go callback with a single argunent 'foo'
58+ fmt.Println (ret) // Output: 3
5659```
5760
61+ ### Resolve JavaScript Promise in Go
62+
63+ ``` go
64+ ctx := v8.NewContext ()
65+ ret , _ := ctx.RunScript (" Promise.resolve('yoo')" , " promise.js" ) // js return a promise object
66+
67+ // get promise result in Go
68+ p , _ := ret.AsPromise ()
69+ fmt.Println (p.Result ().String ()) // Output: "yoo"
70+ ```
71+
72+
5873### Update a JavaScript object from Go
5974
6075``` go
0 commit comments