*A Promises is an object representing the eventual completion of an asynchronous operation.
1.Pending: The initial state, neither fulfilled nor rejected.
2.Fulfilled: The operation completed successfully.
3.Rejected: The operation failed.
let myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Operation was successful!");
} else {
reject("Operation failed.");
}
});
myPromise
.then((message) => {
console.log(message); // "Operation was successful!"
})
.catch((error) => {
console.error(error); // "Operation failed."
});
*then() is executed when the promise is fulfilled.
*catch() is executed when the promise is rejected.
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => { resolve("Promise fulfilled!"); }, 2000);
});
myPromise
.then(message => {
console.log(message);
})
.catch(error => {
console.error('There has been a problem with the promise:', error);
});
Promises allow for cleaner and more linear code compared to nested callbacks.
Errors can be handled using a dedicated .catch() method, simplifying error management.
Promises help prevent deeply nested structures, making the code easier to read and maintain.
Promises are the foundation for the async/await syntax, allowing asynchronous code to be written in a synchronous style.
Promises can improve performance by allowing multiple asynchronous operations to run concurrently.
The above is the detailed content of Promises in java script. For more information, please follow other related articles on the PHP Chinese website!