codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🌐

JavaScript

46 / 65 topics
44JavaScript Callbacks45JavaScript setTimeout and setInterval46JavaScript Promises47JavaScript Promise Chaining48JavaScript async and await49JavaScript Event Loop
Tutorials/JavaScript/JavaScript Promises
🌐JavaScript

JavaScript Promises

Updated 2026-05-12
30 min read

JavaScript Promises

Asynchronous operations are a fundamental part of modern web development. They allow your code to run without blocking the main thread, enabling smoother user experiences and efficient resource utilization. In JavaScript, Promises provide a way to handle asynchronous operations in a more organized and manageable manner.

In this tutorial, you'll learn how to create and consume Promises using the then(), catch(), and finally() methods. By the end of this guide, you'll have a solid understanding of how to work with Promises in your JavaScript applications.

Introduction

Promises are objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value. They are essential for handling tasks like API requests, file operations, or any other asynchronous task where the result is not immediately available.

Understanding Promises is crucial because they simplify error handling and make your code more readable and maintainable. In this tutorial, we'll explore how to create Promises, handle their resolution using then() and catch(), and perform cleanup actions with finally().

Core Content

Creating a Promise

A Promise in JavaScript is created using the Promise constructor, which takes an executor function as an argument. This executor function has two parameters: resolve and reject. These are functions that you call to either fulfill or reject the Promise, respectively.

Here's a simple example of creating a Promise:

createPromise.js
1const myPromise = new Promise((resolve, reject) => {
2setTimeout(() => {
3 const success = true; // Simulate an asynchronous operation
4 if (success) {
5 resolve('Operation succeeded!');
6 } else {
7 reject('Operation failed!');
8 }
9}, 2000);
10});

In this example:

  • We create a new Promise that simulates an asynchronous operation using setTimeout.
  • After 2 seconds, the operation is considered successful (success = true), and we call resolve() with a success message.
  • If the operation were to fail, we would call reject() with an error message.

Consuming a Promise

Once you have a Promise, you can consume it using the then(), catch(), and finally() methods. These methods allow you to handle the resolved value, catch any errors, and perform cleanup actions, respectively.

Using then()

The then() method is used to specify what should happen when a Promise is fulfilled (resolved). It takes two optional arguments: a callback for the resolved value and another for the rejected reason.

Here's how you can use then() to handle the result of our previous Promise:

consumePromise.js
1myPromise
2.then((result) => {
3 console.log(result); // Output: Operation succeeded!
4})
5.catch((error) => {
6 console.error(error);
7});

In this example:

  • We call then() on myPromise.
  • The first callback function logs the resolved value to the console.
  • The second callback function (optional) would handle any errors.

Using catch()

The catch() method is used to handle any errors that occur during the Promise's execution. It takes a single argument: a callback function for handling the rejected reason.

Here's how you can use catch():

useCatch.js
1myPromise
2.then((result) => {
3 console.log(result);
4})
5.catch((error) => {
6 console.error(error); // Output: Operation failed!
7});

In this example:

  • We call catch() after then().
  • The callback function logs the error message to the console.

Using finally()

The finally() method is used to specify a block of code that should run regardless of whether the Promise was fulfilled or rejected. This is useful for cleanup actions, such as closing files or releasing resources.

Here's how you can use finally():

useFinally.js
1myPromise
2.then((result) => {
3 console.log(result);
4})
5.catch((error) => {
6 console.error(error);
7})
8.finally(() => {
9 console.log('Operation completed.');
10});

In this example:

  • We call finally() after both then() and catch().
  • The callback function logs a message indicating that the operation has completed.

Combining then(), catch(), and finally()

You can chain these methods together to handle different outcomes of a Promise. Here's an example:

combinedMethods.js
1myPromise
2.then((result) => {
3 console.log(result);
4})
5.catch((error) => {
6 console.error(error);
7})
8.finally(() => {
9 console.log('Operation completed.');
10});

In this example:

  • We handle the resolved value with then().
  • We handle any errors with catch().
  • We perform cleanup actions with finally().

Common Mistakes

  1. Forgetting to return a Promise in then(): If you return a non-Promise value from a then() callback, it will be wrapped in a resolved Promise automatically. However, if you need to chain further asynchronous operations, make sure to return a Promise.
  2. Not handling errors with catch(): Always include a catch() method to handle any unexpected errors that might occur during the execution of your Promise.
  3. Misusing finally() for conditional logic: The finally() block should be used only for cleanup actions and not for branching logic based on the outcome of the Promise.

Practical Example

Let's create a practical example where we fetch data from an API using Promises:

fetchData.js
1function fetchData(url) {
2return new Promise((resolve, reject) => {
3 const xhr = new XMLHttpRequest();
4 xhr.open('GET', url);
5 xhr.onload = () => {
6 if (xhr.status === 200) {
7 resolve(xhr.responseText);
8 } else {
9 reject(new Error(`Request failed with status ${xhr.status}`));
10 }
11 };
12 xhr.onerror = () => {
13 reject(new Error('Network error'));
14 };
15 xhr.send();
16});
17}
18
19fetchData('https://api.example.com/data')
20.then((data) => {
21 console.log(data);
22})
23.catch((error) => {
24 console.error(error);
25})
26.finally(() => {
27 console.log('Fetch operation completed.');
28});

In this example:

  • We define a fetchData function that returns a Promise.
  • Inside the Promise, we use XMLHttpRequest to fetch data from a given URL.
  • We handle the resolved value with then(), any errors with catch(), and perform cleanup actions with finally().

Summary

ConceptDescription
Creating PromisesUse the Promise constructor with an executor function that calls resolve() or reject().
Consuming PromisesUse then() to handle resolved values, catch() to handle errors, and finally() for cleanup actions.
Chaining MethodsChain then(), catch(), and finally() methods together to handle different outcomes of a Promise.

What's Next?

Now that you have a solid understanding of Promises, the next step is to learn how to chain multiple Promises together using Promise chaining. This allows you to perform a series of asynchronous operations in sequence, making your code more organized and efficient.

In the next tutorial, we'll explore how to use then() chains to handle complex sequences of asynchronous tasks, ensuring that each task completes before moving on to the next one. Stay tuned!


PreviousJavaScript setTimeout and setIntervalNext JavaScript Promise Chaining

Recommended Gear

JavaScript setTimeout and setIntervalJavaScript Promise Chaining