我编写了独立调用多个http请求并合并结果的go代码。

有时组合方法会缺少值。

func profile(req *http.Request)  (UserMe, error, UserRating, error) {

    wgcall := &sync.WaitGroup{}

    uChan := make(chan ResUser)
    rChan := make(chan ResRating)

        // variable inits
    var meResp UserMe
    var ratingResp UserRating

    go func() {
        res := <-uChan
                meResp = res.Value
    }()

    go func() {
        res := <-rChan
                ratingResp = res.Value
    }()

    wgcall.Add(2)
    go me(req, wgcall, uChan)
    go rate(req, wgcall, rChan)

    wgcall.Wait()

    logrus.Info(meResp)  // sometimes missing
    logrus.Info(ratingResp) // sometimes missing

    return meResp, meErr, ratingResp, ratingErr
}

但是 me 和 rating 调用会按预期返回来自 api 请求的值。

func me(req *http.Request, wg *sync.WaitGroup, ch chan ResUser) {
    defer wg.Done()

    // http call return value correclty
    me := ...
    ch <- ResUser{
        Value := // value from rest
    }
    logrus.Info(fmt.Sprintf("User calls  %v" , me))  // always return the values
    close(ch)
}

func rate(req *http.Request, wg *sync.WaitGroup, ch chan ResRating) {
    defer wg.Done()

        // make http call
    rating := ...
    ch <- ResRating{
        Value := // value from rest
    }
    logrus.Info(fmt.Sprintf("Ratings calls %v" , rating)) // always return the values

    close(ch)
}

问题是:配置文件函数上的 meResp 和 ratingResp 并不总是获取值。有时只有 meResp 或 ratingResp,有时两者都符合预期。

但是我和 rate 函数调用总是获取值。

能帮我解决这个问题吗?