Created
November 12, 2017 06:57
-
-
Save drgomesp/fc867eec2395134d97489aa66fb1d4e7 to your computer and use it in GitHub Desktop.
Example of a very basic promises implementation in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"log" | |
"sync" | |
"time" | |
) | |
// Promise ... | |
type Promise struct { | |
fn func() error | |
err error | |
wg sync.WaitGroup | |
} | |
// Then ... | |
func (p *Promise) Then(cb func()) *Promise { | |
p.wg.Add(1) | |
go func(p *Promise) { | |
if err := p.fn(); err != nil { | |
p.err = err | |
} | |
p.wg.Done() | |
}(p) | |
p.wg.Wait() | |
if p.err == nil { | |
cb() | |
} | |
return p | |
} | |
// Err ... | |
func (p *Promise) Error(cb func(err error)) *Promise { | |
if p.err != nil { | |
cb(p.err) | |
} | |
return p | |
} | |
// NewPromise ... | |
func NewPromise(fn func() error) *Promise { | |
return &Promise{fn: fn} | |
} | |
func someAsyncFunction() error { | |
log.Println("someAsyncFunction()") | |
time.Sleep(time.Second * 3) | |
return nil | |
} | |
func someAsyncFunctionWithError() error { | |
log.Println("someAsyncFunctionWithError()") | |
return errors.New("some very bad error") | |
} | |
func main() { | |
promiseThatResolves := NewPromise(someAsyncFunction) | |
promiseThatResolves. | |
Then(func() { | |
log.Println("promise.Then()") | |
}). | |
Error(func(err error) { | |
log.Printf("promise.Error(%v)", err.Error()) | |
}) | |
promiseThatErrors := NewPromise(someAsyncFunctionWithError) | |
promiseThatErrors. | |
Then(func() { | |
log.Println("promise.Then()") | |
}). | |
Error(func(err error) { | |
log.Fatalf("promise.Error(%v)", err.Error()) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment