JavaScript and TypeScript course Β· Module 4: Asynchronous JavaScript

Creating and Handling Promise Objects

12 min read Β·
In this lesson9

In the previous lesson we looked at callback functions and the "callback hell" problem that can arise with complex asynchronous operations. Now let's learn about a more modern solution - Promise objects, which provide a more elegant way to handle asynchronicity in JavaScript.

What Are Promise Objects?

A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value. You can think of it as a "promise" to deliver a certain result in the future.

In the context of Jurassic Park, a Promise is like sending a dinosaur DNA sample to the laboratory for analysis. The laboratory does not return results immediately - instead it gives you a ticket number representing a "promise" to deliver results when the analysis is complete.

A Promise can be in one of three states:

  • Pending - initial state, neither fulfilled nor rejected
  • Fulfilled - the operation completed successfully, the Promise was resolved with a value
  • Rejected - the operation failed, the Promise was rejected with a reason (error)

Creating a Promise

Creating a new Promise in JavaScript looks like this:

const dnaAnalysisPromise = new Promise((resolve, reject) => {
  // Simulating dinosaur DNA analysis (takes 3 seconds)
  console.log("Analyzing dinosaur DNA sample...");

  setTimeout(() => {
    const successRate = Math.random();

    if (successRate > 0.2) {
      // Analysis completed successfully
      const results = {
        species: "Velociraptor",
        age: "Approximately 68 million years",
        diet: "Carnivore",
        geneticMarkers: ["ACGT-237", "TGGC-118", "GACT-339"]
      };

      resolve(results); // Fulfilling the promise
    } else {
      // Analysis failed
      reject(new Error("DNA sample damaged or insufficient")); // Rejecting the promise
    }
  }, 3000);
});

In the example above:

  1. We create a new Promise object, which takes an executor function with two arguments: resolve and reject
  2. Inside the executor function we perform the asynchronous operation (simulated by setTimeout)
  3. If the operation succeeds, we call resolve(result) to fulfill the promise
  4. If the operation fails, we call reject(reason) to reject the promise

Using a Promise - then, catch, and finally

To handle the result of a Promise, we use the then(), catch(), and finally() methods:

console.log("Sending sample to the laboratory...");

dnaAnalysisPromise
  .then(results => {
    console.log("DNA analysis completed successfully!");
    console.log(`Species: ${results.species}`);
    console.log(`Age: ${results.age}`);
    console.log(`Diet: ${results.diet}`);
    console.log("Genetic markers:", results.geneticMarkers.join(", "));
    return results; // We can return a value that will be passed to the next .then()
  })
  .catch(error => {
    console.error("DNA analysis error:", error.message);
    return "No data"; // Return a default value in case of error
  })
  .finally(() => {
    console.log("DNA analysis procedure complete - regardless of outcome.");
    // finally takes no arguments and returns nothing
  });

console.log("Continuing work while DNA is being analyzed...");

Result (on success):

Sending sample to the laboratory...
Analyzing dinosaur DNA sample...
Continuing work while DNA is being analyzed...
(after 3 seconds)
DNA analysis completed successfully!
Species: Velociraptor
Age: Approximately 68 million years
Diet: Carnivore
Genetic markers: ACGT-237, TGGC-118, GACT-339
DNA analysis procedure complete - regardless of outcome.
  • then() - takes a callback function that will be called when the Promise is fulfilled (resolved). The callback receives the value with which the Promise was resolved.
  • catch() - takes a callback function that will be called when the Promise is rejected. The callback receives the error with which the Promise was rejected.
  • finally() - takes a callback function that will be called when the Promise completes, regardless of whether it was fulfilled or rejected. The callback receives no arguments.

Promise Chaining

One of the greatest advantages of Promises is the ability to chain asynchronous operations. Each call to .then() returns a new Promise, allowing the creation of sequences of asynchronous operations without nesting.

Let's imagine the process of creating a new dinosaur in Jurassic Park:

function fetchDNAFromDatabase(speciesId) {
  return new Promise((resolve, reject) => {
    console.log(`Fetching DNA for species ID: ${speciesId}...`);
    setTimeout(() => {
      if (speciesId > 0) {
        resolve(`dna_sequence_${speciesId}`);
      } else {
        reject(new Error("Invalid species ID"));
      }
    }, 1000);
  });
}

function prepareEmbryo(dnaSequence) {
  return new Promise((resolve, reject) => {
    console.log(`Preparing embryo from DNA sequence: ${dnaSequence}...`);
    setTimeout(() => {
      if (dnaSequence.includes("dna_sequence")) {
        resolve(`embryo_${dnaSequence}`);
      } else {
        reject(new Error("Invalid DNA sequence"));
      }
    }, 1500);
  });
}

function incubateEgg(embryo) {
  return new Promise((resolve, reject) => {
    console.log(`Incubating egg with embryo: ${embryo}...`);
    setTimeout(() => {
      if (embryo.includes("embryo_")) {
        resolve(`dino_baby_${embryo.replace("embryo_", "")}`);
      } else {
        reject(new Error("Invalid embryo"));
      }
    }, 2000);
  });
}

function raiseDinosaur(baby) {
  return new Promise((resolve, reject) => {
    console.log(`Raising young dinosaur: ${baby}...`);
    setTimeout(() => {
      if (baby.includes("dino_baby_")) {
        resolve(`adult_dino_${baby.replace("dino_baby_", "")}`);
      } else {
        reject(new Error("Invalid young dinosaur"));
      }
    }, 1500);
  });
}

// Using a promise chain
console.log("Starting the dinosaur creation process...");

fetchDNAFromDatabase(5)
  .then(dna => {
    console.log(`DNA fetched: ${dna}`);
    return prepareEmbryo(dna); // Return a new Promise
  })
  .then(embryo => {
    console.log(`Embryo prepared: ${embryo}`);
    return incubateEgg(embryo); // Return a new Promise
  })
  .then(baby => {
    console.log(`Dinosaur hatched: ${baby}`);
    return raiseDinosaur(baby); // Return a new Promise
  })
  .then(adultDino => {
    console.log(`Dinosaur ready to be introduced to the park: ${adultDino}`);
  })
  .catch(error => {
    console.error("Error in dinosaur creation process:", error.message);
  })
  .finally(() => {
    console.log("Dinosaur creation process complete.");
  });

Compare that with the callback version, which would look something like this:

fetchDNAFromDatabase(5, function(error, dna) {
  if (error) {
    console.error("Error fetching DNA:", error.message);
    console.log("Dinosaur creation process complete.");
    return;
  }

  console.log(`DNA fetched: ${dna}`);
  prepareEmbryo(dna, function(error, embryo) {
    if (error) {
      console.error("Error preparing embryo:", error.message);
      console.log("Dinosaur creation process complete.");
      return;
    }

    console.log(`Embryo prepared: ${embryo}`);
    incubateEgg(embryo, function(error, baby) {
      if (error) {
        console.error("Error incubating egg:", error.message);
        console.log("Dinosaur creation process complete.");
        return;
      }

      console.log(`Dinosaur hatched: ${baby}`);
      raiseDinosaur(baby, function(error, adultDino) {
        if (error) {
          console.error("Error raising dinosaur:", error.message);
          console.log("Dinosaur creation process complete.");
          return;
        }

        console.log(`Dinosaur ready to be introduced to the park: ${adultDino}`);
        console.log("Dinosaur creation process complete.");
      });
    });
  });
});

As you can see, the Promise version is much more readable and easier to maintain.

Converting Callback-Based Functions to Promises

We often need to work with APIs or libraries that use callback-based functions. We can convert them to Promises using a wrapper function:

// Callback-based function (Node-style)
function fetchEnclosureData(enclosureId, callback) {
  setTimeout(() => {
    if (enclosureId <= 0) {
      callback(new Error("Invalid enclosure ID"));
      return;
    }

    const enclosureData = {
      id: enclosureId,
      name: `Enclosure ${enclosureId}`,
      area: 1000 * enclosureId,
      type: enclosureId % 2 === 0 ? "Terrestrial" : "Aquatic"
    };

    callback(null, enclosureData);
  }, 1000);
}

// Convert to Promise
function fetchEnclosureDataPromise(enclosureId) {
  return new Promise((resolve, reject) => {
    fetchEnclosureData(enclosureId, (error, data) => {
      if (error) {
        reject(error); // Reject the Promise on error
      } else {
        resolve(data); // Resolve the Promise with data
      }
    });
  });
}

// Using the Promise version
fetchEnclosureDataPromise(3)
  .then(data => {
    console.log("Enclosure data:", data);
  })
  .catch(error => {
    console.error("Error:", error.message);
  });

This pattern is so common that Node.js offers a built-in util.promisify() function to automatically convert callback-based functions to functions that return Promises.

Static Promise Methods

JavaScript provides several static methods on the Promise object that are very useful in various scenarios:

Promise.resolve() and Promise.reject()

These methods create a Promise that is immediately resolved or rejected with a given value:

// Immediate resolution
const resolvedPromise = Promise.resolve("Dinosaur data");

resolvedPromise.then(data => {
  console.log("Resolved with:", data); // "Resolved with: Dinosaur data"
});

// Immediate rejection
const rejectedPromise = Promise.reject(new Error("No access to dinosaur"));

rejectedPromise.catch(error => {
  console.error("Rejected with:", error.message); // "Rejected with: No access to dinosaur"
});

Promise.all()

Takes an array of promises and returns a new promise that resolves when all promises in the array resolve, or rejects when any one of them rejects:

// Fetching data about three dinosaurs in parallel
const dino1Promise = fetchDinosaurData(1);
const dino2Promise = fetchDinosaurData(2);
const dino3Promise = fetchDinosaurData(3);

Promise.all([dino1Promise, dino2Promise, dino3Promise])
  .then(results => {
    // results is an array of results in promise order
    console.log("All dinosaur data fetched:");
    console.log("Dinosaur 1:", results[0]);
    console.log("Dinosaur 2:", results[1]);
    console.log("Dinosaur 3:", results[2]);

    // We can now do something with all data at once
    const totalWeight = results.reduce((sum, dino) => sum + dino.weight, 0);
    console.log(`Total weight of all dinosaurs: ${totalWeight} kg`);
  })
  .catch(error => {
    // If even one promise rejects, the entire operation fails
    console.error("Failed to fetch all dinosaur data:", error.message);
  });

Promise.race()

Takes an array of promises and returns a new promise that resolves or rejects with the result of the first promise to settle:

// Simulating monitoring of different park systems
function monitorFence() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (Math.random() > 0.8) {
        reject(new Error("Fence failure in sector B!"));
      } else {
        resolve("Fence operating normally");
      }
    }, 1000 + Math.random() * 4000); // 1-5 seconds
  });
}

function monitorPower() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (Math.random() > 0.9) {
        reject(new Error("Main power failure!"));
      } else {
        resolve("Power operating normally");
      }
    }, 1000 + Math.random() * 4000); // 1-5 seconds
  });
}

function monitorCameras() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (Math.random() > 0.7) {
        reject(new Error("Camera signal lost in sector D!"));
      } else {
        resolve("Cameras operating normally");
      }
    }, 1000 + Math.random() * 4000); // 1-5 seconds
  });
}

// We want to know the first alert that appears
Promise.race([
  monitorFence(),
  monitorPower(),
  monitorCameras()
])
  .then(status => {
    console.log("First system status:", status);
  })
  .catch(error => {
    console.error("ALARM! First detected problem:", error.message);
    // Trigger emergency procedures here
    triggerEmergencyProcedure();
  });

function triggerEmergencyProcedure() {
  console.log("Triggering emergency procedure...");
  // Emergency procedure code
}

Promise.allSettled()

Introduced in ES2020, takes an array of promises and returns a new promise that resolves when all promises in the array complete (either resolved or rejected):

// Monitoring all park systems
Promise.allSettled([
  monitorFence(),
  monitorPower(),
  monitorCameras()
])
  .then(results => {
    console.log("Status of all systems:");

    // Each result has status 'fulfilled' or 'rejected'
    results.forEach((result, index) => {
      const systemNames = ["Fence", "Power", "Cameras"];

      if (result.status === 'fulfilled') {
        console.log(`${systemNames[index]}: OK - ${result.value}`);
      } else {
        console.log(`${systemNames[index]}: ERROR - ${result.reason.message}`);
      }
    });

    // Check if any system raised an alarm
    const failures = results.filter(result => result.status === 'rejected');
    if (failures.length > 0) {
      console.log(`WARNING: ${failures.length} system failures detected!`);
      triggerEmergencyProcedure();
    }
  });

Error Handling in Promises

Proper error handling is critical, especially in asynchronous code. Promises provide a unified way to handle errors using the catch() method:

fetchDNAFromDatabase(-1) // Invalid ID, will cause an error
  .then(dna => {
    console.log(`DNA fetched: ${dna}`);
    return prepareEmbryo(dna);
  })
  .then(embryo => {
    console.log(`Embryo prepared: ${embryo}`);
    return incubateEgg(embryo);
  })
  .then(baby => {
    console.log(`Dinosaur hatched: ${baby}`);
    return raiseDinosaur(baby);
  })
  .then(adultDino => {
    console.log(`Dinosaur ready to be introduced to the park: ${adultDino}`);
  })
  .catch(error => {
    // This catch handles errors from all preceding Promises
    console.error("Error in dinosaur creation process:", error.message);

    // We can log errors, notify the user, or take corrective action here
    notifyLabForResearch();

    // We can also return a value to be passed to the next .then()
    return "Dinosaur creation attempt failed";
  })
  .then(message => {
    // This .then() will execute after .catch()
    console.log(message); // "Dinosaur creation attempt failed"

    // We can initiate cleanup procedures or take alternative actions here
    return restartProcedure();
  })
  .catch(error => {
    // This catch handles errors from restartProcedure()
    console.error("Restart error:", error.message);
  });

function notifyLabForResearch() {
  console.log("Notifying laboratory about DNA problem...");
}

function restartProcedure() {
  console.log("Restarting procedure with backup DNA...");
  return "Procedure restarted";
}

Important rules for error handling in Promises:

  1. The catch() method catches errors from all preceding then() methods
  2. If an exception is thrown inside a .then() function, the Promise will be rejected with that exception
  3. You can have multiple catch() methods in a Promise chain to handle different types of errors
  4. After catch() you can continue the chain with more then() methods

Common Promise Pitfalls

1. Forgetting to Return Promises

A common mistake is forgetting to return a Promise from a function, leading to unexpected behavior:

// Wrong - not returning the Promise from the function
function fetchAndSaveData(id) {
  fetchDinosaurData(id) // This returns a Promise, but we do not propagate it
    .then(data => {
      return saveData(data); // This Promise is not visible outside
    });

  // The function does not explicitly return a value, so it returns undefined by default
}

// Correct - returning the Promise
function fetchAndSaveData(id) {
  return fetchDinosaurData(id) // Returning the Promise
    .then(data => {
      return saveData(data); // This Promise is now part of the chain
    });
}

2. Not Handling Errors

Unhandled rejected Promises can cause hard-to-diagnose problems:

// Bad - no error handling
fetchDinosaurData(999) // ID does not exist
  .then(data => {
    // This code will not execute when the Promise is rejected
    displayData(data);
  });
// If the Promise is rejected, the error is not handled!

// Good - always handle errors
fetchDinosaurData(999)
  .then(data => {
    displayData(data);
  })
  .catch(error => {
    console.error("Failed to fetch data:", error.message);
    displayError(error);
  });

3. Promise Hell

Although Promises help avoid Callback Hell, you can fall into a similar trap by nesting Promises instead of chaining them:

// Bad - nesting Promises (Promise Hell)
fetchDinosaurData(1)
  .then(dino => {
    fetchEnclosureData(dino.enclosureId) // Nested Promise
      .then(enclosure => {
        fetchStaff(enclosure.id) // Another nested Promise
          .then(staff => {
            console.log("Dinosaur data:", dino);
            console.log("Enclosure data:", enclosure);
            console.log("Staff:", staff);
          });
      });
  });

// Good - chaining Promises
fetchDinosaurData(1)
  .then(dino => {
    dinoData = dino; // Save data for later use
    return fetchEnclosureData(dino.enclosureId); // Return Promise
  })
  .then(enclosure => {
    enclosureData = enclosure; // Save data for later use
    return fetchStaff(enclosure.id); // Return Promise
  })
  .then(staff => {
    console.log("Dinosaur data:", dinoData);
    console.log("Enclosure data:", enclosureData);
    console.log("Staff:", staff);
  })
  .catch(error => {
    console.error("An error occurred:", error.message);
  });

Summary

Promises are a powerful JavaScript mechanism for handling asynchronous operations, offering many advantages over traditional callbacks:

  1. Better readability - chaining instead of nesting
  2. Better error management - unified error handling via .catch()
  3. More predictable flow - easier sequencing of asynchronous operations
  4. Easier parallel operations - methods like Promise.all() and Promise.race()

Promises form the foundation for an even newer async mechanism in JavaScript - async/await, which we will cover in future lessons. In Jurassic Park, as in real programming, good management of asynchronous operations is the key to building reliable and maintainable systems.

In the next exercise we will see how to chain Promises and build more complex asynchronous flows.

Code for this lesson: index.js
// Multi-Species Counter - Species Counter
console.log("DINOSAUR SPECIES COUNTER\n");

// Function counting dinosaurs by species
function countSpecies(dinosaurs) {
  const counter = {};

  for (let dino of dinosaurs) {
    if (counter[dino]) {
      counter[dino]++;
    } else {
      counter[dino] = 1;
    }
  }

  return counter;
}

// Function displaying report
function displaySpeciesReport(counter) {
  console.log("=== SPECIES REPORT ===\n");

  for (let species in counter) {
    const count = counter[species];
    const emoji = getSpeciesEmoji(species);
    console.log(`${emoji} ${species}: ${count} individuals`);
  }

  const total = Object.values(counter).reduce((sum, count) => sum + count, 0);
  console.log(`\nTotal: ${total} dinosaurs`);
}

function getSpeciesEmoji(species) {
  const emojis = {
    'T-Rex': '',
    'Velociraptor': '',
    'Triceratops': '',
    'Brachiosaurus': '',
    'Stegosaurus': 'β—†'
  };
  return emojis[species] || '';
}

// Test
const parkDinosaurs = [
  'T-Rex', 'T-Rex', 'T-Rex',
  'Velociraptor', 'Velociraptor', 'Velociraptor', 'Velociraptor',
  'Triceratops', 'Triceratops',
  'Brachiosaurus',
  'Stegosaurus', 'Stegosaurus', 'Stegosaurus'
];

const speciesCount = countSpecies(parkDinosaurs);
displaySpeciesReport(speciesCount);

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What does the setTimeout function do?

  2. 2. What is callback hell?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Vertical ordering

    Arrange the steps of handling an asynchronous operation in JavaScript:

  • Code editor

    Write a function that accepts a callback and invokes it with dinosaur data.

  • Horizontal ordering

    Arrange the elements of a delayed function call:

  • Code editor

    Create a Promise that resolves after a delay with dinosaur status data, or rejects if the sensor is not responding.

  1. Put in orderAsynchronous Operation Handling Steps
  2. QuestionsetTimeout
  3. QuestionCallback Hell
  4. QuestionPromise States
  5. Coding taskPractice: Callback Functions
  6. Put in ordersetTimeout Syntax
  7. Coding taskPractice: Creating a Promise

Useful articles