Documentation
¶
Overview ¶
Package eventloop provides a thread-safe event loop for JavaScript execution.
The event loop ensures that all Goja runtime operations occur on a single goroutine, preventing race conditions. It also manages async operations through a wait group mechanism.
Basic Usage ¶
el := eventloop.NewEventLoop(vm)
el.RunOnLoop(func() {
vm.RunString(`console.log("Hello")`)
})
el.Start() // Blocks until all work is done
Async Operations ¶
When starting an async operation (HTTP request, timer, etc.), use WGAdd to indicate pending work and WGDone when complete:
el.WGAdd(1)
go func() {
time.Sleep(time.Second)
el.RunOnLoop(func() {
vm.RunString(`console.log("Delayed")`)
el.WGDone()
})
}()
The event loop automatically stops when all pending operations complete.
Promises ¶
CreatePromise returns a JavaScript Promise along with resolve/reject functions that properly integrate with the event loop:
promise, resolve, reject := el.CreatePromise()
go func() {
result, err := doAsyncWork()
if err != nil {
reject(err)
} else {
resolve(result)
}
}()
return promise
Index ¶
- type EventLoop
- func (el *EventLoop) Context() context.Context
- func (el *EventLoop) CreatePromise() (promise *goja.Object, resolve func(interface{}), reject func(interface{}))
- func (el *EventLoop) RunOnLoop(f func())
- func (el *EventLoop) SetAutoStop(enable bool)
- func (el *EventLoop) Shutdown(timeout context.Context) error
- func (el *EventLoop) Start()
- func (el *EventLoop) Stop()
- func (el *EventLoop) WGAdd(n int)
- func (el *EventLoop) WGDone()
- type RejectionHandler
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type EventLoop ¶
type EventLoop struct {
VM *goja.Runtime
// OnUnhandledRejection is called when a Promise rejects without a catch handler
OnUnhandledRejection RejectionHandler
// contains filtered or unexported fields
}
EventLoop manages the execution of tasks in the JS engine
func NewEventLoop ¶
NewEventLoop creates a new event loop for a goja runtime
func (*EventLoop) CreatePromise ¶
func (el *EventLoop) CreatePromise() (promise *goja.Object, resolve func(interface{}), reject func(interface{}))
CreatePromise returns a JS promise that can be resolved from Go
func (*EventLoop) RunOnLoop ¶
func (el *EventLoop) RunOnLoop(f func())
RunOnLoop schedules a function to run on the JS thread. Safe for concurrent use.
func (*EventLoop) SetAutoStop ¶
SetAutoStop controls whether the loop shuts down automatically when idle
func (*EventLoop) Shutdown ¶
Shutdown gracefully shuts down the event loop, waiting for pending jobs
func (*EventLoop) Start ¶
func (el *EventLoop) Start()
Start runs the event loop. It blocks until the loop is stopped or all tasks are done.
func (*EventLoop) Stop ¶
func (el *EventLoop) Stop()
Stop terminates the event loop and cancels its context
type RejectionHandler ¶
type RejectionHandler func(err error)
RejectionHandler is called when a Promise is rejected without a handler