DEV Community

Sufian | DevDose
Sufian | DevDose

Posted on Edited on

How to Cancel Remaining Requests When Promise.all Fails in JavaScript

Your app has a dashboard that loads three things at the same time: the user's profile, their orders, and some recommendations. You fetch them in parallel, and you use Promise.all to wait for all three.

async function getJson(path) {
  const response = await fetch(URL + path);
  if (!response.ok) {
    throw new Error(`${path} returned HTTP ${response.status}`);
  }
  return response.json();
}

await Promise.all([
  getJson("/profile"),
  getJson("/orders"),
  getJson("/recommendations"),
]);
Enter fullscreen mode Exit fullscreen mode

URL is your API's base address, such as https://api.example.com. getJson is a small wrapper around fetch that throws an error when the server answers with a failure status.

Now suppose the profile request fails, so the page shows an error and stops. You'd expect the other two requests to stop too, but they keep running. Promise.all only changes when you hear about the failure. Your backend goes on executing their queries for a page that is already gone.

What happens

I ran this exact code against a small local server that logs what it does (a small test server I wrote for this). In this test /profile fails with HTTP 500 after 200 ms, while /orders and /recommendations are slow queries that take 1,000 and 1,500 ms. The server's log:

[ 222ms]     server: /profile finished, sending response
[ 229ms] Dashboard failed: /profile returned HTTP 500
[1023ms]     server: /orders finished, sending response
[1522ms]     server: /recommendations finished, sending response
Enter fullscreen mode Exit fullscreen mode

The page gave up at the "Dashboard failed" line, but the server kept working for another 800 to 1,300 ms and sent responses nobody wanted. Under heavy traffic, those unwanted queries pile up.

The fix: AbortController

AbortController is built into Node.js and every modern browser. It has two parts:

  • controller.abort() is the switch.
  • controller.signal is a flag that fetch watches. When the switch is pressed, fetch cancels the request and closes the connection.

You can see both parts in a few lines:

const controller = new AbortController();
const signal = controller.signal;

console.log(signal.aborted); // false

controller.abort();          // press the switch

console.log(signal.aborted); // true
Enter fullscreen mode Exit fullscreen mode

Output:

false
true
Enter fullscreen mode Exit fullscreen mode

fetch reads this flag for you. Each fetch call that receives a signal watches it on its own. When the signal is aborted, that fetch stops its request and closes the connection, without needing any other code to tell it to. That is why passing the same signal to every request is enough to cancel all of them.

Three changes make getJson cancellable:

  • It takes a controller argument.
  • It passes controller.signal to fetch.
  • It wraps the request in try/catch. When the request fails, the catch block calls controller.abort() and rethrows the same error, so Promise.all still reports the original failure.
async function getJson(path, controller) {
  try {
    const response = await fetch(URL + path, { signal: controller.signal });
    if (!response.ok) {
      throw new Error(`${path} returned HTTP ${response.status}`);
    }
    return await response.json();
  } catch (error) {
    controller.abort(); // cancel the other requests that share this controller
    throw error;
  }
}
Enter fullscreen mode Exit fullscreen mode

Then create one controller and pass it to all three requests:

const controller = new AbortController();

await Promise.all([
  getJson("/profile", controller),
  getJson("/orders", controller),
  getJson("/recommendations", controller),
]);
Enter fullscreen mode Exit fullscreen mode

When /profile fails, its catch block aborts the controller, which cancels the other two requests sharing it. The error in that catch is whatever made the request fail, here the HTTP 500 error thrown just above it.

The result

Same test, same failing profile call:

[2231ms]     server: /profile finished, sending response
[2235ms] Dashboard failed: /profile returned HTTP 500
[2237ms]     server: /recommendations client disconnected, work cancelled
[2237ms]     server: /orders client disconnected, work cancelled
Enter fullscreen mode Exit fullscreen mode

A few milliseconds after the failure, the server saw both clients hang up and stopped working on them.

Gotchas

  • Pass the controller to every request. A request without it won't be cancelled.
  • Your backend has to notice the disconnect. Aborting closes the connection from the client side. Many frameworks and database drivers react to that, but check yours.
  • Only abort what is safe to abandon. Cancelling a payment request on the client doesn't guarantee the server undoes it, so this works best for reads.

Top comments (0)