experimental promises in go1.18 with generics

async go

a prototype of "promises" in go1.18.

note: this is just an experiment used to test alternate patterns for dealing with asynchronous code in go. i would not recommend adopting this pattern blindly (especially in production environments) until there is a broader consensus in the go community about this. it might turn out that through some hands-on experience that go's native channels/goroutines are a good enough abstraction and there are no gains to be made from building on top of them.

install

should be just a regular package:

go get -u -v code.nkcmr.net/async@latest

usage

promises abstract away a lot of details about how asynchronous work is handled. so if you need for something to be async, simply us a promise:

import (
    "context"
    "code.nkcmr.net/async"
)

type MyData struct {/* ... */}

func AsyncFetchData(ctx context.Context, dataID int64) async.Promise[MyData] {
    return async.NewPromise(func() (MyData, error) {
        /* ... */
        return myDataFromRemoteServer, nil
    })
}

func DealWithData(ctx context.Context) {
    myDataPromise := AsyncFetchData(ctx, 451)
    // do other stuff while operation is not settled
    // once your ready to wait for data:
    myData, err := myDataPromise.Await(ctx)
    if err != nil {/* ... */}
}
Owner
nick comer
programmer, tinkerer, learner.
nick comer
Similar Resources

A library that provides Go Generics friendly "optional" features.

go-optional A library that provides Go Generics friendly "optional" features. Synopsis some := optional.Some[int](123) fmt.Printf("%v\n", some.IsSome(

Dec 20, 2022

Go 1.18 generics use cases and examples

Go 1.18 generics use cases What are generics? See Type Parameters Proposal. How to run the examples? As of today, gotip is the simplest way to run the

Jan 10, 2022

Functional tools in Go 1.18 using newly introduced generics

functools functools is a simple Go library that brings you your favourite functi

Dec 5, 2022

Experimenting with golang generics to implement functional favorites like filter, map, && reduce.

funcy Experimenting with golang generics to implement functional favorites like filter, map, && reduce. 2021-12 To run the tests, you need to install

Dec 29, 2021

A collection of functional operators for golang with generics

fn fn is a collection of go functional operators with generics Getting Started P

Jul 8, 2022

Benchmarks to compare Go Generics

This is a collection of various sorts implemnted both as []int only and as const

Dec 8, 2022

Utility library that uses Go generics mechanism

golang-generics-util Utility library that explores Go generics (1.18) xsync Sync

Dec 11, 2022

CDN-like in-memory cache with shielding, and Go 1.18 Generics

cache CDN-like, middleware memory cache for Go applications with integrated shielding and Go 1.18 Generics. Usage package main import ( "context" "

Apr 26, 2022

Go 1.18 generics based slice and sorts.

genfuncs import "github.com/nwillc/genfuncs" Package genfuncs implements various functions utilizing Go's Generics to help avoid writing boilerplate c

Jan 2, 2023
Comments
  • Data race in Settled

    Data race in Settled

    	// Settled indicates if a call to Await will cause a blocking behavior, or
    	// if the result will be immediately returned.
    	Settled() bool
    

    This method

    func (s *syncPromise[T]) Settled() bool {
    	return atomic.LoadInt32(&s.settled) == 1
    }
    

    will return true once this code has executed

    func (s *syncPromise[T]) resolve(v T) {
    	if atomic.CompareAndSwapInt32(&s.settled, 0, 1) {
    

    but potentially before this code has executed

    		s.result = result[T]{value: v}
    		close(s.done)
    

    which means that this code

    
    func (s *syncPromise[T]) Await(ctx context.Context) (T, error) {
    	select {
    	case <-ctx.Done():
    		var zerov T
    		return zerov, ctx.Err()
    	case <-s.done:
    		return s.result.value, s.result.err
    	}
    }
    

    would block, violating the contract of the interface.

    I think you can solve this in a number of ways... maybe this is one?

    type syncPromise[T any] struct {
    	val  T
    	err  error
    	done chan struct{}
    }
    
    func NewPromise[T any](fn func() (T, error)) Promise[T] {
    	p := &syncPromise[T]{done: make(chan struct{})}
    	go func() { p.val, p.err = fn(); close(p.done) }()
    	return p
    }
    
    func (p *syncPromise[T]) Settled() bool {
    	select {
    	case <-p.done:
    		return true
    	default:
    		return false
    	}
    }
    
    func (p *syncPromise[T]) Await(ctx context.Context) (T, error) {
    	select {
    	case <-p.done:
    		return p.val, p.err
    	case <-ctx.Done():
    		var zero T
    		return zero, ctx.Err()
    	}
    }
    

    edit: golfed it a bit to remove the need for result[T]

Go-generics-simple-doubly-linked-list - A simple doubly linked list implemented using generics (Golang)

Welcome to Go-Generics-Simple-Doubly-Linked-List! Hi, This repository contains a

Jun 30, 2022
A go1.18+ package to (maybe) simplify performing operations on slices in a fluent-like style.

sop ✨ W.I.P. ✨ sop (slices operation) is a go1.18+ package to (maybe) simplify performing operations on slices in a fluent-like style with common oper

Oct 1, 2022
A rule-based tunnel in Go with experimental features.
 A rule-based tunnel in Go with experimental features.

This repository is for archiving only Experimental-Clash A rule-based tunnel in Go with experimental features. Features Local HTTP/HTTPS/SOCKS server

Dec 3, 2021
Code Generation for Functional Programming, Concurrency and Generics in Golang

goderive goderive derives mundane golang functions that you do not want to maintain and keeps them up to date. It does this by parsing your go code fo

Dec 25, 2022
Experiments with Go generics

generics Quick experiments with Go generics algebra, a generic square root function for float, complex and and rational. future, a concurrent cache ("

Dec 31, 2022
Example code for Go generics

go-generics-example Example code for Go generics. Usage $ go build -gcflags=-G=3 Requirements Go 1.17 or later Advertise Go 言語にやってくる Generics は我々に何をも

Dec 30, 2022
Collection of unusual generics usecases in Go

Unusual Generics Type parameters or Generics in Go designed to reduce boilerplate for container data types like lists, graphs, etc. and functions like

Dec 14, 2022
Package truthy provides truthy condition testing with Go generics
Package truthy provides truthy condition testing with Go generics

Truthy Truthy is a package which uses generics (Go 1.18+) to create useful boolean tests and helper functions. Examples // truthy.Value returns the tr

Nov 11, 2022
Go Library for Competitive Programming with Generics

Go Library for Competitive Programming with Generics Go used to be a difficult language to use for competitive programming. However, with the introduc

Dec 21, 2022
Extended library functions using generics in Go.

Just few extended standard library functions for Golang using generics.

Dec 16, 2021