Documentation
¶
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func New ¶
New creates a sobek.Promise that wraps an asynchronous operation. The async function runs in a separate goroutine and can safely interact with JavaScript values through the provided callback. The callback ensures all JavaScript operations happen on the main goroutine.
The callback return:
- result (any): The value to resolve the promise with
- error: If non-nil, the promise will be rejected with this error
If a panic occurs in either the async function or callback, the promise will be rejected with the panic value.
Example usage - implementing an async fetch function:
func main() {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"foo":"bar"}`))
}))
defer server.Close()
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
fetch := func(call sobek.FunctionCall, rt *sobek.Runtime) sobek.Value {
return promise.New(rt, func(callback promise.Callback) {
res, err := http.Get(call.Argument(0).String())
callback(func() (any, error) {
if err != nil {
return nil, err
}
defer res.Body.Close()
data, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
return string(data), nil
})
})
}
var (
value sobek.Value
err error
)
err = js.Run(ctx, func(rt *sobek.Runtime) error {
_ = rt.Set("fetch", fetch)
value, err = rt.RunString(fmt.Sprintf(`fetch("%s")`, server.URL))
return err
})
if err != nil {
panic(err)
}
fmt.Println(value.Export().(*sobek.Promise).Result().Export())
}
Types ¶
Click to show internal directories.
Click to hide internal directories.