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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?