A JavaScript Promise is an object that represents the result of an asynchronous operation. It can tell us whether an operation is completed successfully or has failed.
For example, when you fetch data from an API, the response may take some time. Instead of waiting and blocking other code, you can use a Promise to handle the result when it becomes available.
In this tutorial, you will learn what JavaScript Promises are, how they work, and how to use them with simple examples.
What Is a JavaScript Promise?
A Promise is used to handle operations that may complete in the future.
A Promise has three states:
- Pending: The operation is still in progress.
- Fulfilled: The operation completed successfully.
- Rejected: The operation failed.
Once a Promise is fulfilled or rejected, its state cannot change again.
Creating a Promise in JavaScript
You can create a Promise using the Promise constructor.
const myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Operation completed successfully!");
} else {
reject("Something went wrong!");
}
});
console.log(myPromise);
Here is how it works:
new Promise()creates a new Promise.resolve()marks the Promise as fulfilled.reject()marks the Promise as rejected.- The
successvariable decides which result to return.
Using then() to Handle a Promise
The .then() method runs when a Promise is fulfilled.
const myPromise = new Promise((resolve) => {
resolve("Hello, JavaScript!");
});
myPromise.then((result) => {
console.log(result);
});
Output:
Hello, JavaScript!
You can use .then() to process the result of an asynchronous operation.
Using catch() to Handle Errors
The .catch() method handles a rejected Promise.
const myPromise = new Promise((resolve, reject) => {
reject("Failed to load data!");
});
myPromise
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error);
});
Output:
Failed to load data!
Using .catch() helps you handle errors instead of leaving rejected operations unhandled.
Using finally() with a Promise
The .finally() method runs when the Promise settles, whether it is fulfilled or rejected.
const myPromise = new Promise((resolve) => {
resolve("Data loaded!");
});
myPromise
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error);
})
.finally(() => {
console.log("Operation finished.");
});
Output:
Data loaded!
Operation finished.
The finally() method is useful for hiding loading indicators or cleaning up resources after an operation.
Real-World Example: Fetching API Data
Promises are commonly used when working with APIs.
The following example fetches sample user data from an API.
fetch("https://jsonplaceholder.typicode.com/users/1")
.then((response) => {
if (!response.ok) {
throw new Error("Failed to fetch user");
}
return response.json();
})
.then((user) => {
console.log(user.name);
console.log(user.email);
})
.catch((error) => {
console.error("Error:", error.message);
});
In this example:
fetch()requests data from the API and returns a Promise.- The first
.then()checks the HTTP response and converts it to JSON. - The second
.then()accesses the user’s name and email. .catch()handles network errors and errors thrown in the preceding handlers.
Important: fetch() does not automatically reject its Promise for HTTP errors such as 404 or 500. That is why checking response.ok is useful.
Promise vs Callback
Callbacks and Promises can both handle asynchronous operations, but they work differently.
| Callback | Promise |
|---|---|
| Uses a function passed to another function | Represents a future result |
| Can become difficult to manage when deeply nested | Supports chaining with .then() |
| Error handling depends on the callback pattern | Supports .catch() for rejection handling |
Promises can make asynchronous code easier to organize and maintain.
Conclusion
JavaScript Promises help you handle asynchronous operations such as API requests, file operations, and other tasks that finish in the future.
Remember these three methods:
.then()handles successful results..catch()handles errors..finally()runs after the Promise settles.
Once you understand Promises, learning async/await becomes much easier.
Frequently Asked Questions
1. What is a Promise in JavaScript?
A Promise is an object that represents the eventual success or failure of an asynchronous operation.
2. What are the three states of a Promise?
The three states are pending, fulfilled, and rejected.
3. What is the difference between then() and catch()?
.then() handles fulfillment by default, while .catch() handles rejection.
4. Can a Promise be resolved more than once?
A Promise can have its state settled only once. Later calls to resolve() or reject() do not change that settled state.
5. What is the difference between Promises and async/await?
async/await provides a more readable syntax for working with Promises. An async function always returns a Promise, and await pauses that function until the awaited Promise settles.
6. When should you use Promises?
Use Promises when handling asynchronous tasks such as API requests, database operations through supported libraries, and other operations that may complete in the future.