Skip to content

Instantly share code, notes, and snippets.

@cdimascio
Last active January 7, 2017 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdimascio/57c179fc10f7c626fa99b96dca976250 to your computer and use it in GitHub Desktop.
Save cdimascio/57c179fc10f7c626fa99b96dca976250 to your computer and use it in GitHub Desktop.
Golang Promise simulation
func main() {
person := new(Person)
person.Name = "Carmine"
SavePerson(person).Then(func(obj interface{}) error {
fmt.Printf("Successfully created %v\n", obj)
return nil
}, func(err error) {
fmt.Printf("Failed to create %v\n", err)
}).Then(func(obj interface{}) error {
fmt.Printf("Chain - Do something after Person is created")
return nil
}, func(err error) {
fmt.Printf("Failed %s", err.Error())
})
}
func (promise *Promise) Then(success func(interface{}) error, failure func(error)) *Promise {
result := new(Promise)
result.resolverCh = make(chan interface{})
result.rejectorCh = make(chan error)
go func() {
select {
case res := <-promise.resolverCh:
err := success(res)
if err == nil {
result.resolverCh <- res
} else {
result.rejectorCh <- err
}
case err := <-promise.rejectorCh:
failure(err)
result.rejectorCh <- err
}
}()
return result
}
func SavePerson(person *Person) *Promise {
promise := new(Promise)
promise.resolverCh = make(chan interface{})
promise.rejectorCh = make(chan error)
go func() {
res, err := db.Save(person) // This method is not shown here - imagine it updates a db
if err != nil {
promise.rejectorCh <- err
} else {
promise.resolverCh <- res
}
}()
return promise
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment