playwright-community / playwright-go

Playwright for Go a browser automation library to control Chromium, Firefox and WebKit with a single API.
https://playwright-community.github.io/playwright-go/
MIT License
1.94k stars 145 forks source link

how to waiting multiple api responsed in go-playwright ,like javascript promise.all #323

Open mirkcale opened 1 year ago

mirkcale commented 1 year ago

I wirte an go function to waiting some api responsed and then to do something,here is my code

func waitResponse(dashboardIds []int, page playwright.Page) {
    responses := [5]playwright.Response{}
    wg := sync.WaitGroup{}
    baseUrl := "https://example.com"
    for index, v := range dashboardIds {
        wg.Add(1)
        url := fmt.Sprintf("%s/%d?dashboard_id=114", baseUrl, v)
        idx := index
        v := v
        go func() {
            log.Printf("start request %s\n", url) // 1
            response := page.WaitForResponse(url)
            log.Printf("goroutine get response from %s, index is %d\n", url,idx) // 2
            resBody, _ := response.Body()
            responses[idx] = response
            defer wg.Done()
        }()
        page.On("response", func(res playwright.Response) {
            if res.URL() == url {
                log.Printf("listen get response from %s", url) //3
            }
        })
    }
    wg.Wait()
    log.Printf("all url responded") // 4
}

after run this function,I find 1、3 print every time,but 2 is only print one time(idx is 0), is there something wrong in my code?pls help me,thinks!

I want comment 4 could print