promise

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 25, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func New

func New(rt *sobek.Runtime, async func(callback Callback)) sobek.Value

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())
}

func Reject

func Reject(rt *sobek.Runtime, reason any) sobek.Value

Reject with reason

func Resolve

func Resolve(rt *sobek.Runtime, value any) sobek.Value

Resolve with value

func Result

func Result(value sobek.Value) (any, error)

Result returns the promise result, if it not promise return origin value.

Types

type Callback

type Callback func(func() (any, error))

Callback is a function that receives a function to resolve/reject the promise.

The function return:

  • result (any): The value to resolve the promise with
  • error: If non-nil, the promise will be rejected with this error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL