匿名函数似乎不在Go例程中执行

匿名函数似乎不在Go例程中执行,go,Go,我有以下代码。请特别注意匿名功能: func saveMatterNodes(matterId int, nodes []doculaw.LitigationNode) (bool, error) { var ( err error resp *http.Response ) // Do this in multiple threads for _, node := range nodes { fmt.Prin

我有以下代码。请特别注意匿名功能:

func saveMatterNodes(matterId int, nodes []doculaw.LitigationNode) (bool, error) {

    var (
        err  error
        resp *http.Response
    )

    // Do this in multiple threads
    for _, node := range nodes {
        fmt.Println("in loops")
        go func() {
            postValues := doculaw.LitigationNode{
                Name:        node.Name,
                Description: node.Description,
                Days:        node.Days,
                Date:        node.Date,
                IsFinalStep: false,
                Completed:   false,
                Matter:      matterId}

            b := new(bytes.Buffer)
            json.NewEncoder(b).Encode(postValues)
            resp, err = http.Post("http://127.0.0.1:8001/matterNode/", "application/json", b)
            io.Copy(os.Stdout, resp.Body)

            fmt.Println("Respone from http post", resp)
            if err != nil {
                fmt.Println(err)
            }
        }()

    }

    if err != nil {
        return false, err
    } else {
        return true, nil
    }

}

如果我删除go func{}部分并将代码保留在两者之间,它似乎执行得很好,但当我将其添加回时,它不会执行。知道为什么吗?我最初认为可能是因为它在另一个线程上执行,但事实并非如此,因为我在webservice访问日志中看到它没有执行。

我认为这种行为是因为函数在启动goroutines后不会返回主线程,程序中没有等待他们完成工作的构造。 使用通道、IO操作、sync.WaitGroup等可以将控制权交还给主线程

您可能需要尝试sync.WaitGroup

例如: