Promises are a cleaner way to handle asynchronous operations in JavaScript.
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);
});
Create a promise that simulates an operation, resolves if successful, or rejects with an error message.
then
method?Answers: An object representing the completion or failure of an async operation; handles successful results; use catch
to handle errors.