Wait for slow work

INPUT · Slides

Guarding against async errors

01 / 05

Asynchronous actions fail frequently

Servers go down, Wi-Fi drops, resources disappear (404).

In asynchronous operations, failures happen regularly even when your code is completely correct. Error handling is essential.

02 / 05

Familiar try / catch works directly!

With raw Promises, you chained .catch(). In async / await, the familiar try / catch from Chapter 10 works seamlessly!

When an awaited Promise rejects, control jumps immediately to the catch block.

const run = async () => {  try {    const p = Promise.reject("Network error");    const data = await p;    console.log(data);  } catch (error) {    console.log("Caught error:", error);  }};run();

Result

Caught error: Network error

03 / 05

Continuing safely without crashing

Once handled in catch, execution resumes safely after the block.

You can set fallback values, display notices, or log diagnostics without crashing the entire app.

const run = async () => {  let items = [];  try {    items = await Promise.reject("Server fault");  } catch (error) {    console.log("Using cached fallback");    items = ["Offline data"];  }  console.log(items[0]);};run();

Result

Using cached fallback
Offline data

04 / 05

Cleaning up with finally

Code that must run regardless of success or failure belongs in finally.

Hiding loading spinners or dismissing progress indicators belongs right here in finally.

const run = async () => {  try {    await Promise.resolve("Success");  } finally {    console.log("Load complete");  }};run();

Result

Load complete

05 / 05

Check the key points

Let us review the ideas:

  • Wrap await inside try { }
  • Handle rejections in catch (error) { }
  • Clean up in finally { }
  • Essential convention in real-world frontend engineering

Let us practice handling async errors!