Asynchronous 处理条件异步函数返回数据的惯用方法是什么?

Asynchronous 处理条件异步函数返回数据的惯用方法是什么?,asynchronous,go,goroutine,Asynchronous,Go,Goroutine,我有一个函数,可以作为异步go例程调用,也可以不作为异步go例程调用 func APICall(request *HTTPRequest) *HTTPResponse *HTTPRequest是指向结构的指针,该结构包含构建请求所需的各种数据: type HTTPRequest struct { // Represents a request to the twitter API method string baseurl string urlParams ma

我有一个函数,可以作为异步go例程调用,也可以不作为异步go例程调用

func APICall(request *HTTPRequest) *HTTPResponse
*HTTPRequest
是指向结构的指针,该结构包含构建请求所需的各种数据:

type HTTPRequest struct {
    // Represents a request to the twitter API
    method string
    baseurl string
    urlParams map[string]string
    bodyParams map[string]string
    authParams map[string]string
    responseChan chan *HTTPResponse
}
如果称为goroutine,即传入一个通道;我们构建请求并将响应写入所提供通道的*HTTPResponse对象(也是一个结构)。在没有通道(即非异步)的情况下,接受函数调用的最优雅/惯用的方式是什么

目前,我们在APICall的主体中执行类似的操作来处理这两种函数调用:

if request.responseChan != nil { // If a response channel has been specified, write to that channel
request.responseChan <- &twitterHTTPResponse{body, nil}
return nil // Not returning a struct
} else {
return &twitterHTTPResponse{body, nil} // Return a pointer to a new struct representing the response
}
if request.responseChan!=nil{//如果已指定响应通道,则写入该通道

request.responseChan惯用方法是提供同步API:

type HTTPRequest struct {
    // Represents a request to the twitter API
    method string
    baseurl string
    urlParams map[string]string
    bodyParams map[string]string
    authParams map[string]string
}

func APICall(request *HTTPRequest) *HTTPResponse {
    ...
    return &twitterHTTPResponse{body, nil} 
}
如果调用方需要同时运行调用,则可以轻松创建goroutine。例如:

r := make(chan *HTTPResponse) 
go func() {
    r <- APICall(req)
}()

... do some other work

resp := <- r
r:=make(chan*HTTPResponse)
go func(){

r惯用方法是提供同步API:

type HTTPRequest struct {
    // Represents a request to the twitter API
    method string
    baseurl string
    urlParams map[string]string
    bodyParams map[string]string
    authParams map[string]string
}

func APICall(request *HTTPRequest) *HTTPResponse {
    ...
    return &twitterHTTPResponse{body, nil} 
}
如果调用方需要同时运行调用,则可以轻松创建goroutine。例如:

r := make(chan *HTTPResponse) 
go func() {
    r <- APICall(req)
}()

... do some other work

resp := <- r
r:=make(chan*HTTPResponse)
go func(){

r惯用的方法是编写同步API,让调用方执行来自goroutine的调用。这如何解决是否需要通道的歧义?同步API不使用通道。惯用的方法是从
HTTPRequest
中删除
responeChan
,然后简单地返回 &twitterHTTPResponse{body,nil},err
。惯用的方法是编写同步API并将其留给调用方执行来自goroutine的调用。这如何解决是否需要通道的歧义?同步API不使用通道。惯用的方法是从
HTTPRequestresponeChan
de>并从函数返回
&twitterHTTPResponse{body,nil},err
。感谢Cerise。这是否主要是因为API请求通常涉及使用本身已经高度异步的net/http stdlib?(因此,如果API函数与其他应用程序逻辑正确分离,那么作为goroutine运行它在理论上应该不会带来什么好处?)我更新了答案,以说明为什么同步API是惯用的。net/http客户端API是同步的。谢谢Cerise。这是惯用的,主要是因为API请求通常涉及使用net/http stdlib,而net/http stdlib本身已经是高度异步的吗?(因此,如果API函数与其他应用程序逻辑正确分离,那么作为goroutine运行它在理论上应该不会带来什么好处?)我更新了答案,以描述为什么同步API是惯用的。net/http客户端API是同步的。