Promises
Topic 5JavaScript Part 2 (Async JS)
Promises
Introduction
Promises are the backbone of asynchronous programming in JavaScript. A Promise represents a value that may be available now, later, or never. A Promise is an object that represents the eventual completion or failure of an asynchronous operation. It has three states: Pending, Fulfilled, or Rejected, and provides methods like .then, .catch, and .finally to handle these states.
Key Concepts and Definitions
Promise States
Pending: The initial state. Fulfilled: When the operation is successful. Rejected: When the operation fails.
Promise Methods
.then() - handles fulfilled promises, .catch() - handles rejected promises, .finally() - executes regardless of outcome
Examples
Creating and Handling Promises:
const promiseExample = new Promise((resolve, reject) => {
let success = true; // Simulate success or failure
setTimeout(() => {
if (success) {
resolve('Operation successful');
} else {
reject('Operation failed');
}
}, 2000);
});
promiseExample
.then((message) => console.log(message)) // Logs "Operation successful" after 2 seconds
.catch((error) => console.error(error));Promise Chaining:
new Promise((resolve) => {
setTimeout(() => resolve(5), 1000);
})
.then((value) => value * 2)
.then((result) => console.log(result)); // Logs 10 after 1 secondInterview guide discussion
(0)Join the discussion — login to comment and help other developers.
Login to comment