go-future

module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 4, 2023 License: MIT

README

go-future

This library helps to use goroutines and wait for result.

Usage example

Single Future
Simple usage
fut := future.Run(func() (string, error) {
	time.Sleep(1000 * time.Millisecond)
	return "name", nil
})

// do anything ...

// wait until the process is complete and getResult
result := fut.GetResult()
Handle error
result, err := fut.Get()
if err != nil {
    println("An error occurred.")
}
PassFunction
func ExampleFunc() (string, error) {
    time.Sleep(1000 * time.Millisecond)
    return "name", nil
}

fut := future.Run(ExampleFunc)
result := fut.GetResult()

Multiple Future
Parallel request example
ids := []string{"A", "B", "C", "D", "E"}
futures := make([]*future.Future[string], 5)
for i := range ids {
    id := ids[i]
    f := future.Run(func() (string, error) {
    return APICall(id)
    })
    futures[i] = f
}

// wait all until the process is complete and getResult
results, err := future.GetAll(futures)
if err != nil {
    log.Println("An error occurred...")
    return
}
Parallel request different result example
fut1 := future.Run(func() (any, error) {
    return GetValueA()
})

fut2 := future.Run(func() (any, error) {
    return GetValueB()
})

log.Println("Waiting for future result...")
err := future.WaitFor(fut1, fut2)
if err != nil {
    log.Println("An error occurred...")
    return
}
result1 := future.GetResult[string](fut1)
result2 := future.GetResult[int64](fut2)

Directories

Path Synopsis
examples
test

Jump to

Keyboard shortcuts

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