-
Notifications
You must be signed in to change notification settings - Fork 3.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
doc: Why use Promise.all when await works? #5470
Comments
if
|
Why didn't I see this? ty! |
I'll hijack this issue as it's the first result searching for the need of I'll use the Let's say, we have a Search Input field and a button that triggers the search, eventually making a request to an API ( You would probably write something like this await page.locator("button").click() // search button
await page.waitForResponse("https://example.com/api/search") With the above code, there's a (high) chance that we already received a response from
What we want here is for
const [response] = await Promise.all([
page.locator("button").click(),
page.waitForResponse("https://example.com/api/search")
]); executes both Many Playwright events ( But we're not done yetThe order of the iterable promises inside In short
As a result, we switch around the order const [response] = await Promise.all([
page.waitForResponse("https://example.com/api/search")
page.locator("button").click(),
]); and thereby prevent obscure situations. Long explanationTo understand why the order matters, we need to understand several NodeJS/Programming concepts. If all promises in To understand how progress is made and in NodeJS concurrency, I'd recommend reading up on the
With this knowledge, you will understand that it's important to run the "event listener" before it's counterpart that would trigger the event. BonusThe initial confusion may originate from conventional event listeners, as we know, in JavaScript (e.g. Playwright provides "conventional" event listeners, as we know, but they may lead in many nested layers to achieve the same result. E.g: page.once('response', async response =>{
if(response.url() === "https://example.com/api/search" ){
// additional events have to be nested in here as this now is the scope of the rest of the test
}
})
await page.locator("button").click(), Bonus 2You can also verify/inspect above statements by skipping the additional steps of the await page.locator("button").click({noWaitAfter: true, force: true}) // immediately resolve
await page.waitForResponse("https://example.com/api/search") If the API does not respond immediately, then the above code should work too. However, this likely ends in untrustworthy tests that should not be used. |
in https://playwright.dev/docs/api/class-browsercontext#browsercontextonpage
there is
but this work too in our test:
What is the reason Promise.all is used for this scenario?
edit: corrected code for correctness.
The text was updated successfully, but these errors were encountered: