promise

package
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 2 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Promise Package

The promise package provides a Go-idiomatic, chainable async primitive for Kite applications. It replaces ad-hoc goroutines and ensures that callbacks are executed safely on the main UI thread.

Usage

Promises are created using promise.New, which takes an executor function returning (T, error). The executor receives a context managed by the scheduler.

p := promise.New(func(ctx context.Context) (string, error) {
    // This runs in a background worker pool.
    // The ctx is automatically injected by the scheduler.
    return fetchData(ctx)
})

p.Then(func(data string) {
    // This runs on the main UI thread.
    element.SetText(data)
}, func(err error) {
    // This also runs on the main UI thread.
    log.Error(err)
})

Wrapping Synchronous Functions

If you have existing synchronous functions, you can easily convert them into asynchronous functions that return a *Promise using the Wrap and WrapWithProps utility functions. This is especially useful for creating reusable fetchers for the wind package.

// 1. A function that only takes a context
func fetchConfigSync(ctx context.Context) (Config, error) { /* ... */ }
var FetchConfigAsync = promise.Wrap(fetchConfigSync)

// 2. A function that takes a context and an arguments/properties struct
type UserProps struct { ID int }
func fetchUserSync(ctx context.Context, props UserProps) (User, error) { /* ... */ }
var FetchUserAsync = promise.WrapWithProps(fetchUserSync)

Both wrappers preserve the supplied context's values, deadline, and cancellation, and also cancel the execution context when the scheduler shuts down. A call canceled before execution is rejected without invoking the wrapped function. Once execution starts, the function must honor its context (for example, by passing it to http.NewRequestWithContext).

promise.New still supplies only the scheduler's context. Calling Await(ctx) limits the wait; it does not cancel the underlying operation. Use a wrapper or explicitly propagate your request context when operation cancellation matters.

Thread Safety

  • Background Execution: The executor function runs in the engine's background worker pool, preventing UI freezes during expensive operations.
  • Main-Thread Callbacks: .Then(), .Catch(), and .Finally() callbacks are automatically queued as microtasks on the main thread. This makes it safe to mutate the DOM or component state directly within these callbacks.
  • State Management: The promise state machine is internally synchronized using a sync.Mutex, making it safe to register callbacks from any goroutine.

Integration

The promise package is automatically integrated with the Kite engine. When you call kitex.Render, the scheduler is automatically wired, and any promises created thereafter will use the engine's bounded worker pool.

Documentation

Overview

Package promise provides a lightweight, generic Promise<T> implementation for asynchronous operations in the Kite terminal UI engine.

Promise

Promise[T any] represents the eventual completion or failure of an asynchronous operation. It is created via New(), which runs the executor on a background scheduler. The scheduler (set via SetScheduler) controls background execution, microtask queues, and macrotask queues.

Methods

  • Then(fn, err) registers callbacks for fulfillment and rejection.
  • Catch(err) registers only a rejection handler.
  • Finally(fn) registers a handler for both settle paths.
  • Await(ctx) blocks until the promise settles or the context is cancelled.

Factory Functions

  • Resolved[T](val) returns an immediately fulfilled promise.
  • RejectedPromise[T](err) returns an immediately rejected promise.

Scheduler

The Scheduler interface controls where and how executor functions run. A global scheduler can be set via SetScheduler; if none is set, promises fall back to a simple goroutine and synchronous dispatch.

Example:

p := promise.New(func(ctx context.Context) (string, error) {
     return "hello", nil
})
p.Then(func(s string) {
	fmt.Println(s)
}, nil)

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ClearSchedulerIf

func ClearSchedulerIf(s Scheduler) bool

ClearSchedulerIf clears the global scheduler to nil if and only if it currently matches s. Returns true if the global scheduler was cleared.

func SetScheduler

func SetScheduler(s Scheduler)

SetScheduler sets the global scheduler used by all promises.

func Spawn

func Spawn(task func(ctx context.Context)) bool

Spawn launches a long-lived or unbounded task outside the bounded worker pool via the active global scheduler, binding its context and shutdown lifecycle to that scheduler. Returns false if task is nil or the scheduler is already stopped. When no scheduler is registered, Spawn runs task in a new goroutine with context.Background() and returns true.

func Wrap

func Wrap[T any](fn func(context.Context) (T, error)) func(context.Context) *Promise[T]

Wrap converts a synchronous function that takes a context into an asynchronous function that returns a Promise. The context provided when calling the returned function supplies its values, deadline, and cancellation. Scheduler shutdown also cancels the execution context. The wrapped function must honor cancellation.

func WrapWithProps

func WrapWithProps[P any, T any](fn func(context.Context, P) (T, error)) func(context.Context, P) *Promise[T]

WrapWithProps converts a synchronous function that takes a context and a properties payload into an asynchronous function that returns a Promise. It preserves the caller's context and scheduler cancellation in the same way as Wrap.

Types

type Promise

type Promise[T any] struct {
	// contains filtered or unexported fields
}

Promise represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

func New

func New[T any](executor func(context.Context) (T, error)) *Promise[T]

New creates a new Promise and executes the executor in the background. The context provided to the executor is managed by the scheduler.

Example
package main

import (
	"context"
	"fmt"
	"strconv"

	"github.com/masterkeysrd/kite/promise"
)

func main() {
	port := promise.New(func(context.Context) (int, error) {
		return strconv.Atoi("8080")
	})

	value, err := port.Await(context.Background())
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("port:", value)
}
Output:
port: 8080

func RejectedPromise

func RejectedPromise[T any](err error) *Promise[T]

Rejected returns a new Promise that is already rejected with the given error.

func Resolved

func Resolved[T any](val T) *Promise[T]

Resolved returns a new Promise that is already fulfilled with the given value.

func (*Promise[T]) Await

func (p *Promise[T]) Await(ctx context.Context) (T, error)

Await blocks the caller until the promise is settled or the context is cancelled.

func (*Promise[T]) Catch

func (p *Promise[T]) Catch(onRejected func(error)) *Promise[T]

Catch registers a callback for when the promise is rejected.

func (*Promise[T]) Finally

func (p *Promise[T]) Finally(onFinally func()) *Promise[T]

Finally registers a callback that is executed when the promise is settled.

func (*Promise[T]) Then

func (p *Promise[T]) Then(onFulfilled func(T), onRejected func(error)) *Promise[T]

Then registers callbacks for when the promise is fulfilled or rejected. If the promise is already settled, the callback is queued immediately.

type Scheduler

type Scheduler interface {
	// RunBackground executes a task on a background worker pool.
	// The provided context is managed by the scheduler.
	RunBackground(task func(ctx context.Context))
	// Spawn launches a long-lived or unbounded task in its own goroutine outside
	// the fixed-size worker pool, while binding its context and shutdown lifecycle
	// to the scheduler.
	Spawn(task func(ctx context.Context))
	// QueueMicrotask schedules a task to run as a microtask on the main thread.
	QueueMicrotask(task func())
	// QueueMacrotask schedules a task to run as a macrotask on the main thread.
	QueueMacrotask(task func())
}

type State

type State int
const (
	Pending State = iota
	Fulfilled
	Rejected
)

Jump to

Keyboard shortcuts

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