我有以下 go-duktape 代码:
package main
import (
"fmt"
"gopkg.in/olebedev/go-duktape.v3"
"time"
)
func main() {
code := "function test(){log('testing');log('testing2');done();done();};"
resp := make(chan string)
ctx := duktape.New()
go doExec(code, ctx, resp)
select {
case r := <-resp:
fmt.Printf("%s\n", r)
case <-time.After(5 * time.Second):
fmt.Printf("Execution timeout\n")
}
kill(ctx)
close(resp)
}
func kill(ctx *duktape.Context) {
ctx.DestroyHeap()
ctx.Destroy()
}
func doExec(code string, ctx *duktape.Context, resp chan string) {
ctx.PushGlobalGoFunction("done", func(c *duktape.Context) int {
resp <- "We're done!!"
return 0
})
ctx.PushGlobalGoFunction("log", func(c *duktape.Context) int {
fmt.Println(c.SafeToString(-1))
return 0
})
err := ctx.PevalString(code + ";try{test()}catch(e){log('Error in execution');}")
if err != nil {
fmt.Printf("Error is %s\n", err.Error())
resp <- "Error in exec"
}
}
我的目标是在FIRST 函数调用之后终止程序,之后done()
不再执行任何函数。但是,如果我运行以下代码,它会出现恐慌,因为它done()
被调用了两次,并且第二次调用尝试在已关闭的通道上写入。如何确保它在第一次done()
通话后终止?
谢谢!