doutang6600 2018-04-01 23:51
浏览 51
已采纳

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

I have a function which may or may not be called as an asynchronous go-routine.

func APICall(request *HTTPRequest) *HTTPResponse

*HTTPRequest is a pointer to a struct which contains various pieces of data required in order to build a request:

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
}

If called as a goroutine, i.e a channel is passed in; we build the request and write the response into the *HTTPResponse object (also a struct) of the provided channel. What is the most graceful / idiomatic way to accept a call to the function without a channel (ie. Not async)

At the moment, we do something like this within the body of APICall to deal with both kinds of function call:

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
}

Are we along the right lines?

  • 写回答

1条回答 默认 最新

  • duanhui3759 2018-04-02 02:51
    关注

    The idiomatic approach is to provide a synchronous 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} 
    }
    

    The caller an can easily create a goroutine if it needs to run the call concurrently. For example:

    r := make(chan *HTTPResponse) 
    go func() {
        r <- APICall(req)
    }()
    
    ... do some other work
    
    resp := <- r
    

    Synchronous APIs are idiomatic for a couple of reasons:

    • Synchronous APIs are easier to use and understand.
    • Synchronous APIs don't make incorrect assumptions about how the application is managing concurrency. For example, the application may want to use a wait group to wait for completion instead of receiving on a channel as assumed by the API.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000