ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Promise Chain with Error Handling

JavaScript

Goal -- WPM

Ready
Exercise Algorithm Area
1function fetchData(url) {
2return new Promise((resolve, reject) => {
3setTimeout(() => {
4if (url === "invalid-url") {
5reject(new Error("Invalid URL provided"));
6} else {
7resolve({ data: `Content from ${url}` });
8}
9}, 500);
10});
11}
12
13function processData(data) {
14return new Promise((resolve, reject) => {
15setTimeout(() => {
16if (!data || !data.data) {
17reject(new Error("No data to process"));
18} else {
19const processed = data.data.toUpperCase();
20resolve({ processed });
21}
22}, 300);
23});
24}
25
26function displayResult(result) {
27return new Promise((resolve) => {
28setTimeout(() => {
29console.log("Final Result:", result.processed);
30resolve();
31}, 200);
32});
33}
34
35function executePipeline(url) {
36fetchData(url)
37.then(processData)
38.then(displayResult)
39.catch(error => {
40console.error("Pipeline failed:", error.message);
41});
42}
43
44executePipeline("http://example.com/data");
45executePipeline("invalid-url");
Algorithm description viewbox

Promise Chain with Error Handling

Algorithm description:

This algorithm demonstrates a robust promise chaining pattern for asynchronous operations. It simulates fetching data, processing it, and then displaying the result, with comprehensive error handling at each stage. This is crucial for building reliable applications that interact with external resources or perform complex asynchronous tasks.

Algorithm explanation:

The `executePipeline` function orchestrates a series of asynchronous operations using `Promise.then()`. Each step (`fetchData`, `processData`, `displayResult`) returns a promise, allowing subsequent operations to be chained. The `.catch()` block acts as a central error handler, capturing any rejections from any preceding promise in the chain. This pattern ensures that if any part of the asynchronous flow fails, the error is gracefully handled, preventing application crashes. The use of `setTimeout` simulates real-world asynchronous delays. The `fetchData` function checks for an invalid URL, and `processData` checks for missing input data, representing common edge cases.

Pseudocode:

function executePipeline(url):
  call fetchData(url)
  if promise resolves:
    call processData(resolved_data)
    if promise resolves:
      call displayResult(processed_data)
    else (promise rejects):
      log error message
  else (promise rejects):
    log error message