【发布时间】:2016-06-25 20:51:30
【问题描述】:
我正在尝试在 Go 中实现 Promise,这与 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.
}
如何执行以下操作:
- 运行一个goroutine,它将
Promise返回到主goroutine右边 离开。 在等待时在主例程上异步执行某些操作 任何要发送到
Promise.Result或Promise.Error一旦发送了一些东西,从 goroutine 返回并进行 频道可供阅读。
【问题讨论】:
标签: asynchronous go promise channel