I'm trying to implement Promise in Go which would be similar to that in Javascript.
type Promise struct {
Result chan string
Error chan error
}
func NewPromise() (*Promise) {
r := make(chan string, 1)
e := make(chan error, 1)
return &Promise{
Result: r,
Error: e,
}
}
func main() {
var p = NewPromise()
go func(p *Promise) {
time.Sleep(time.Duration(5)*time.Second)
p.Result <- "done"
}(p)
if <- p.Result {
fmt.Println(<-p.Result)
}
// Is it possible to do something else here while wait for 5s?
// Once Promise is fulfilled after 5s, the Result is available.
}
How do I do the following:
- Run a goroutine, which return
Promiseto the main goroutine right away. Asynchronously do something on the main routine while wait for anything to be sent to either
Promise.ResultorPromise.ErrorOnce something is sent, return from the goroutine and make that channel available to be read.