Promises in JavaScript
Promises are a cleaner way to handle asynchronous operations in JavaScript.
Creating a Promise
A promise represents the completion (or failure) of an asynchronous operation and its resulting value:
let myPromise = new Promise(function(resolve, reject) {
let success = true;
if (success) {
resolve("Operation successful");
} else {
reject("Operation failed");
}
});
myPromise
.then(function(value) {
console.log(value); // Outputs: Operation successful
})
.catch(function(error) {
console.log(error);
});
Activity
Try It Yourself!
Create a promise that simulates an operation, resolves if successful, or rejects with an error message.
Quiz
Quick Quiz
- What is a promise in JavaScript?
- What is the purpose of the
thenmethod? - How do you handle errors in promises?
Answers: An object representing the completion or failure of an async operation; handles successful results; use catch to handle errors.