Created
January 19, 2020 23:14
-
-
Save doron2402/76f2931f6c2c007cdb07470193f429a5 to your computer and use it in GitHub Desktop.
Promises implementation using Go (Golang)
This file contains 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" | |
"fmt" | |
) | |
type Promise struct { | |
successChannel chan interface{} | |
failureChannel chan error | |
} | |
type Message struct { | |
ID int | |
Value float64 | |
} | |
func main() { | |
msg1 := new(Message) | |
msg1.ID = 2 | |
msg1.Value = 123.12318123 | |
SaveMessage(msg1).Then(func(obj interface{}) error { | |
msg1 := obj.(*Message) | |
fmt.Printf("Message %d", msg1.ID) | |
return nil | |
}, func(err error) { | |
fmt.Printf("Error: " + err.Error()) | |
}) | |
fmt.Scanln() | |
} | |
// SaveMessage -> receieve a pointer to a message and returns a promise | |
func SaveMessage(msg *Message) *Promise { | |
result := new(Promise) | |
result.successChannel = make(chan interface{}, 1) | |
result.failureChannel = make(chan error, 1) | |
go func() { | |
if msg.ID%2 == 0 { | |
result.failureChannel <- errors.New("Fail to save message") | |
} else { | |
result.successChannel <- msg | |
} | |
}() | |
return result | |
} | |
func (this *Promise) Then(success func(interface{}) error, failure func(error)) *Promise { | |
result := new(Promise) | |
result.successChannel = make(chan interface{}, 1) | |
result.failureChannel = make(chan error, 1) | |
go func() { | |
select { | |
case obj := <-this.successChannel: | |
newErr := success(obj) | |
if newErr != nil { | |
result.failureChannel <- newErr | |
} else { | |
result.successChannel <- obj | |
} | |
case err := <-this.failureChannel: | |
failure(err) | |
result.failureChannel <- err | |
} | |
}() | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment