@@ -40,21 +40,36 @@ if _, err := ctx2.RunScript("multiply(3, 4)", "main.js"); err != nil {
40
40
}
41
41
```
42
42
43
- ### JavaScript function with Go callback
43
+ ### Call Go function from JavaScript
44
44
45
45
``` go
46
46
iso := v8.NewIsolate () // create a new VM
47
47
// 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
51
52
})
53
+
52
54
global := 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
54
56
ctx := 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
56
59
```
57
60
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
+
58
73
### Update a JavaScript object from Go
59
74
60
75
``` go
0 commit comments