how to get a resolve value in a promise?
hey team, i have some confusions in these code
vm := goja.New()
promise, err := vm.RunString(`
async function sum(a, b) {
return a+b;
}
`)
if err != nil {
panic(err)
}
add, ok := goja.AssertFunction(vm.Get("sum"))
if !ok {
panic("not a function")
}
value, _ := add(goja.Undefined(), vm.ToValue(40), vm.ToValue(2))
return value
in this example, the sum Function return a [object, Promise], but i want to get a Resolved value, please tell me how do i?
Export to promise
func main() {
vm := goja.New()
_, err := vm.RunString(`
async function sum(a, b) {
return a+b;
}
`)
if err != nil {
panic(err)
}
add, ok := goja.AssertFunction(vm.Get("sum"))
if !ok {
panic("not a function")
}
value, _ := add(goja.Undefined(), vm.ToValue(40), vm.ToValue(2))
var result any
if p, ok := value.Export().(*goja.Promise); ok {
switch p.State() {
case goja.PromiseStateRejected:
panic(p.Result().String())
case goja.PromiseStateFulfilled:
result = p.Result().Export()
default:
panic("unexpected promise state pending")
}
}
fmt.Println(result)
}
Export to promise
func main() { vm := goja.New() _, err := vm.RunString(` async function sum(a, b) { return a+b; } `) if err != nil { panic(err) } add, ok := goja.AssertFunction(vm.Get("sum")) if !ok { panic("not a function") } value, _ := add(goja.Undefined(), vm.ToValue(40), vm.ToValue(2)) var result any if p, ok := value.Export().(*goja.Promise); ok { switch p.State() { case goja.PromiseStateRejected: panic(p.Result().String()) case goja.PromiseStateFulfilled: result = p.Result().Export() default: panic("unexpected promise state pending") } } fmt.Println(result) }
I would like to ask a question,the promise is async,so in goja in golang it is sync?If the execution is not completed when the results are obtained,it is true?
Export to promise
func main() { vm := goja.New() _, err := vm.RunString(` async function sum(a, b) { return a+b; } `) if err != nil { panic(err) } add, ok := goja.AssertFunction(vm.Get("sum")) if !ok { panic("not a function") } value, _ := add(goja.Undefined(), vm.ToValue(40), vm.ToValue(2)) var result any if p, ok := value.Export().(*goja.Promise); ok { switch p.State() { case goja.PromiseStateRejected: panic(p.Result().String()) case goja.PromiseStateFulfilled: result = p.Result().Export() default: panic("unexpected promise state pending") } } fmt.Println(result) }I would like to ask a question,the promise is async,so in goja in golang it is sync?If the execution is not completed when the results are obtained,it is true?
It's async, you can also see https://github.com/dop251/goja/blob/28ee0ee714f3e8218c14e2cd2d7a67ec94848c21/builtin_promise.go#L592-L611