JavaScript Promises: A Beginner’s Guide

Ashish Misal
3 min read5 days ago

JavaScript is a powerful language for building web applications, and one of its core features is asynchronous programming. Promises are a fundamental part of handling asynchronous operations in JavaScript, making it easier to manage tasks like API calls, file reading, or database queries. In this article, we’ll explore what Promises are, how they work, and why they are essential in modern JavaScript development.

What is a Promise?

A Promise is an object representing the eventual completion (or failure) of an asynchronous operation. It acts as a placeholder for a value that will be available in the future. A Promise can be in one of three states:

  1. Pending — The initial state, meaning the operation is still in progress.
  2. Fulfilled — The operation completed successfully, and a result is available.
  3. Rejected — The operation failed, and an error is returned.

Once a Promise is either fulfilled or rejected, it is considered settled, and its state does not change.

Creating a Promise

You can create a Promise using the Promise constructor, which takes a function (executor) with two arguments: resolve and reject.

const myPromise = new Promise((resolve, reject) => {
let success = true; // Simulating a condition
if (success) {
resolve("Operation successful!");
} else {
reject("Operation failed.");
}
});

Handling a Promise

Promises use .then(), .catch(), and .finally() methods to handle the results of an asynchronous operation.

Using .then() for Success

The .then() method is used when a Promise is fulfilled:

myPromise.then((message) => {
console.log(message); // Output: Operation successful!
});

Using .catch() for Errors

The .catch() method handles cases where a Promise is rejected:

myPromise.catch((error) => {
console.error(error); // Output: Operation failed.
});

Using .finally() for Cleanup

The .finally() method runs regardless of the outcome (fulfilled or rejected), making it useful for cleanup operations:

myPromise.finally(() => {
console.log("Operation completed.");
});

Chaining Promises

You can chain multiple .then() methods to handle sequential asynchronous operations:

fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error fetching data:", error));

This structure ensures that each step executes only after the previous one completes.

Using async/await with Promises

ES6 introduced async/await, which simplifies working with Promises by making asynchronous code look more synchronous:

async function fetchData() {
try {
let response = await fetch("https://api.example.com/data");
let data = await response.json();
console.log(data);
} catch (error) {
console.error("Error fetching data:", error);
}
}

fetchData();

Promise Methods

Promise.all() – Run Multiple Promises in Parallel

Executes multiple Promises simultaneously and returns results when all have completed:

Promise.all([
fetch("https://api.example.com/data1").then(res => res.json()),
fetch("https://api.example.com/data2").then(res => res.json())
]).then(results => {
console.log("Data1:", results[0]);
console.log("Data2:", results[1]);
}).catch(error => console.error("Error:", error));

Promise.race() – Return First Resolved Promise

Returns the result of the first Promise that settles (either fulfilled or rejected):

Promise.race([
fetch("https://api.example.com/data1"),
fetch("https://api.example.com/data2")
]).then(result => console.log("First resolved:", result))
.catch(error => console.error("Error:", error));

Promise.allSettled() – Wait for All Promises to Settle

Waits for all Promises to complete, whether they are fulfilled or rejected:

Promise.allSettled([
fetch("https://api.example.com/data1"),
fetch("https://api.example.com/data2"),
fetch("https://api.example.com/data3")
]).then(results => console.log(results));

Promise.any() – Return First Fulfilled Promise

Returns the first fulfilled Promise (ignores rejected ones):

Promise.any([
fetch("https://api.example.com/data1"),
fetch("https://api.example.com/data2")
]).then(result => console.log("First successful:", result))
.catch(error => console.error("All failed:", error));

Promises are a crucial part of modern JavaScript for handling asynchronous operations efficiently. They prevent callback hell, improve code readability, and work seamlessly with async/await. Understanding Promises will help you write better, more maintainable JavaScript code. Start using Promises in your projects today and experience the power of asynchronous programming!

Feel Free to Reach me on LinkedIn: Ashish Misal.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Ashish Misal
Ashish Misal

Written by Ashish Misal

Software Developer | Expert in JavaScript, Node.js, React, MERN Stack | Building scalable apps | Mentor for developers | Passionate about innovation

No responses yet

Write a response