Last active
January 7, 2017 15:20
-
-
Save cdimascio/57c179fc10f7c626fa99b96dca976250 to your computer and use it in GitHub Desktop.
Golang Promise simulation
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
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()) | |
}) | |
} |
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
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 | |
} |
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
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