What are Promises?
Promises in JavaScript are objects that represent the eventual completion (or failure) of an asynchronous operation. They serve as placeholders for future results and simplify working with asynchronous code. Here's an example:
Promises in JavaScript are objects that represent the eventual completion (or failure) of an asynchronous operation. They serve as placeholders for future results and simplify working with asynchronous code. Here's an example:
const fetchData = new Promise((resolve, reject) => {
// Simulating an asynchronous operation
setTimeout(() => {
const data = 'Hello, Promises!';
resolve(data); // Resolving the promise with the data
}, 2000);
});
fetchData.then((data) => {
console.log(data); // Output: Hello, Promises!
});
Promises have three states: pending, fulfilled, and rejected. They start in the pending state and can transition to either fulfilled (when the operation is successful) or rejected (when an error occurs). Here's an example showcasing promise states and handling errors:
const promise = new Promise((resolve, reject) => {
const randomNumber = Math.random();
if (randomNumber < 0.5) {
resolve('Success!');
} else {
reject(new Error('Failure!'));
}
});
promise
.then((result) => {
console.log(result); // Output: Success!
})
.catch((error) => {
console.error(error); // Output: Error: Failure!
});
Promises can be chained together to perform sequential asynchronous operations. Each then method in the chain handles the result of the previous promise. Here's an example:
const fetchUserData = () => {
return new Promise((resolve) => {
setTimeout(() => {
const user = { name: 'John Doe', age: 25 };
resolve(user);
}, 1000);
});
};
const processData = (user) => {
return new Promise((resolve) => {
setTimeout(() => {
user.isAdmin = true;
resolve(user);
}, 1000);
});
};
fetchUserData()
.then(processData)
.then((user) => {
console.log(user); // Output: { name: 'John Doe', age: 25, isAdmin: true }
});
Promises can be composed using Promise.all and Promise.race methods. Promise.all waits for all promises to resolve, while Promise.race waits for the first promise to resolve or reject. Here's an example:
const fetchUserData = () => {
return new Promise((resolve) => {
setTimeout(() => {
const user = { name: 'John Doe', age: 25 };
resolve(user);
}, 1000);
});
};
const fetchPostData = () => {
return new Promise((resolve) => {
setTimeout(() => {
const post = { title: 'JavaScript Promises', likes: 10 };
resolve(post);
}, 1500);
});
};
Promise.all([fetchUserData(), fetchPostData()])
.then(([user, post]) => {
console.log(user, post);
// Output: { name: 'John Doe', age: 25 } { title: 'JavaScript Promises', likes: 10 }
});
In this example, we have two functions, fetchUserData and fetchPostData, which return promises that resolve with user and post data, respectively. We use Promise.all to wait for both promises to resolve, and the .then method to handle the results as an array[user, post]. Finally, we log the user and post data to the console.