How can I wait for an ajax request and process the result?
You can wait on both simultaneously and handle whichever occurs first:
await Promise.race([
page.waitForNavigation({ waitUntil: "networkidle0" }),
page.waitForSelector(".Error")
]);
if (await page.$(".Error")) {
// there was an error
} else {
// the page changed
}
The accepted answer isn't waiting for a request but waiting for a selector. That kind of hacky-way wasn't doing it for me.
Waiting a promise resolution coupled with the request response status is the easiest way to achieve it.
await Promise.all( [
page.click( selector ), // ... action
page.waitForResponse( response => response.status() === 200 ), // ... wait for network
] );
- Source @ https://github.com/puppeteer/puppeteer/blob/main/docs/api.md#pagewaitforresponseurlorpredicate-options
HTTP response status codes
Response | Description |
---|---|
200 OK |
The HTTP 200 OK success status response code indicates that the request has succeeded. A 200 response is cacheable by default. |
- Source @ https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200