lecture 8 of 140 completed

Running work together with Promise.all

Start waiting for a response before the click that causes it. Then learn when to collect every failure with Promise.allSettled.

What you'll learn

  • Why the wait for a response must start before the action
  • How Promise.all runs independent work together
  • When Promise.allSettled is the better choice for a report

A test clicks Search in Shelf and then waits for the search response, so it can check what the server sent. Most runs pass. Some runs wait until the timeout and fail, although the search worked.

import { test, expect } from '@playwright/test';

test('search asks the server for the title', async ({ page }) => {
  await page.goto('/books');
  await page.getByRole('button', { name: 'Search' }).click();
  const response = await page.waitForResponse('**/api/search*');  // may start too late
  expect(response.status()).toBe(200);
});

waitForResponse waits for a response that arrives after you call it. On a fast server, the response has already arrived by the time the click returns. The test is then waiting for a second response that never comes.

The wait has to be started before the click. You can start work without awaiting it yet. Keep the promise in a variable and await it later.

import { test, expect } from '@playwright/test';

test('search asks the server for the title', async ({ page }) => {
  await page.goto('/books');
  const responsePromise = page.waitForResponse('**/api/search*');
  await page.getByRole('button', { name: 'Search' }).click();
  const response = await responsePromise;
  expect(response.status()).toBe(200);
});
  1. page.waitForResponse(...) starts listening and returns a promise. There is no await, so the test moves on while the listening continues.
  2. The click causes the request.
  3. await responsePromise waits for the listening to finish. If the response has already arrived, this line continues at once.

This is the one place where leaving out await on purpose is correct. The promise is not lost. It is stored and awaited two lines later.

The same idea in plain code:

let listener = null;

function waitForResponse() {
  return new Promise((resolve) => {
    listener = resolve;
  });
}

function click() {
  if (listener) {
    listener("200 OK");
  }
  return Promise.resolve();
}

async function listenFirst() {
  const responsePromise = waitForResponse();
  await click();
  const response = await responsePromise;
  console.log("listen first: " + response);
}

listenFirst();
listen first: 200 OK

If click() ran before waitForResponse(), listener would still be null and the response would be missed.

Promise.all: start together, wait for all

When several pieces of work do not depend on each other, you can start them all and wait once. Promise.all takes an array of promises and returns one promise. That promise is fulfilled with an array of the results, in the same order as the promises you gave it.

function findBook(title) {
  console.log("looking up " + title);
  return Promise.resolve({ title, copies: title.length });
}

async function run() {
  const books = await Promise.all([findBook("Dune"), findBook("Emma"), findBook("Ulysses")]);
  for (const book of books) {
    console.log(book.title + ": " + book.copies);
  }
}

run();
looking up Dune
looking up Emma
looking up Ulysses
Dune: 4
Emma: 4
Ulysses: 7

All three lookups start before any result is used. The language guarantees that the results come back in the order of the array, whichever lookup finishes first.

Use this for setup that is truly independent, such as creating three test users through an API. Do not use it for steps on one page. Two clicks sent to the same page at the same time are not a test of anything a user can do.

One failure ends Promise.all

If any promise in the array is rejected, the promise from Promise.all is rejected with that error. The other results are thrown away.

function findBook(title) {
  if (title === "Hamlet" || title === "Faust") {
    return Promise.reject(new Error("No book titled " + title));
  }
  return Promise.resolve({ title });
}

async function run() {
  try {
    await Promise.all([findBook("Dune"), findBook("Hamlet"), findBook("Faust")]);
  } catch (error) {
    console.log("stopped: " + error.message);
  }
}

run();
stopped: No book titled Hamlet

Two lookups failed and the report names one. For a single test step that is fine, because one failure is enough to fail the test.

Promise.allSettled: collect every result

Sometimes you want the whole picture. A check that visits twenty links should report every broken link, not only the first one. Promise.allSettled waits for every promise and never rejects. It gives one object per promise.

function findBook(title) {
  if (title === "Hamlet" || title === "Faust") {
    return Promise.reject(new Error("No book titled " + title));
  }
  return Promise.resolve({ title });
}

async function run() {
  const results = await Promise.allSettled([findBook("Dune"), findBook("Hamlet"), findBook("Faust")]);
  for (const result of results) {
    if (result.status === "fulfilled") {
      console.log("found " + result.value.title);
    } else {
      console.log("failed: " + result.reason.message);
    }
  }
}

run();
found Dune
failed: No book titled Hamlet
failed: No book titled Faust

Each object has a status. A fulfilled one has a value. A rejected one has a reason, which is the error.

There is a trap here. allSettled never throws, so a test that only awaits it always passes. After you have collected the failures, the test must still fail when there are any. Count them and throw.

Remember this

Start a wait before the action that causes what you are waiting for, and await the stored promise afterwards. Promise.all runs independent work together and stops at the first failure. Promise.allSettled gives you every result, and then failing the test is your job.

Reference: Promise.allSettled on MDN.

now prove it

Reading is the setup. Solve this exercise in the editor. We run your code on each case and compare what it prints with the expected output.