我试图在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右侧 离开. 在等待的同时异步地在主 routine 上执行某些操作 任何要寄到
Promise.Result
或Promise.Error
的东西一旦有东西被发送,从goroutine返回并完成