原文: http://labs.strava.com/blog/futures-in-golang/
promise/future是一个非常重要的异步编程模型,它可以让我们摆脱传统的回调陷阱,从而使用更加优雅、清晰的方式进行异步编程
package main
import (
"net/http"
"io/ioutil"
"fmt"
)
func main() {
url := "http://www.google.com"
future := Future(func() (interface{}, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
})
// do many other things
b, err := future()
body, _ := b.([]byte)
fmt.Printf("response length: %d", len(body))
fmt.Printf("request error: %v", err)
}
func Future(f func() (interface{}, error)) func() (interface{}, error) {
var result interface{}
var err error
c := make(chan struct{}, 1)
go func() {
defer close(c)
result, err = f()
}()
return func() (interface{}, error) {
<-c
return result, err
}
}
有疑问加站长微信联系(非本文作者)