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

标签 asynchronous go goroutine

我有一个函数可以调用也可以不调用为异步 go-routine。

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调用,即传入一个channel;我们构建请求并将响应写入所提供 channel 的 *HTTPResponse 对象(也是一个结构)。在没有 channel 的情况下接受对函数的调用的最优雅/最惯用的方式是什么(即非异步)

目前,我们在 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
}

我们走的路对吗?

最佳答案

惯用的方法是提供同步 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

由于以下几个原因,同步 API 是惯用的:

  • 同步 API 更易于使用和理解。
  • 同步 API 不会对应用程序如何管理并发做出错误的假设。例如,应用程序可能希望使用 WaitGroup 来等待完成,而不是像 API 假定的那样在 channel 上接收。

关于asynchronous - 处理条件异步函数的返回数据的惯用方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49603738/

相关文章:

ruby - 使用 ruby​​ 的异步 HTTP 请求

go - golang 中 server.GracefulStop() 的行为

go - 为什么 Goroutine 在 Busy Loop 之后还能被调度?

parallel-processing - 去函数 channel 中的死锁

python - 在 Python 中使用异步

Angular HttpInterceptor - 处理异步响应

go - 为什么这行得通,我在最大索引后 slice 1 而没有收到错误?

go - 如何有效地停止 gocron 作业?

javascript - async.series 和 javascript 变量

go - channel 结束父例程后返回