Promises in java script

t_shivakumar_0dc86c6486c

T Shiva Kumar

Posted on August 20, 2024

Promises in java script

what is promises

*A Promises is an object representing the eventual completion of an asynchronous operation.

States of a Promise

A Promise can be in one of three states:

1.Pending: The initial state, neither fulfilled nor rejected.
2.Fulfilled: The operation completed successfully.
3.Rejected: The operation failed.

Creating a Promise

let myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Operation was successful!");
} else {
reject("Operation failed.");
}
});

To handle the outcome of a promise, you use the then() and catch() methods:

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.

Example of promises

const myPromise = new Promise((resolve, reject) => {

setTimeout(() => {

    resolve("Promise fulfilled!");
}, 2000); 
Enter fullscreen mode Exit fullscreen mode

});

myPromise
.then(message => {
console.log(message);
})
.catch(error => {
console.error('There has been a problem with the promise:', error);
});

Advantages of Promises:-

1.Improved Readability:

Promises allow for cleaner and more linear code compared to nested callbacks.

2.Better Error Handling:

Errors can be handled using a dedicated .catch() method, simplifying error management.

3.Avoids Callback Hell:

Promises help prevent deeply nested structures, making the code easier to read and maintain.

4.Supports Async/Await:

Promises are the foundation for the async/await syntax, allowing asynchronous code to be written in a synchronous style.

5.Enhanced Performance:

Promises can improve performance by allowing multiple asynchronous operations to run concurrently.

💖 💪 🙅 🚩
t_shivakumar_0dc86c6486c
T Shiva Kumar

Posted on August 20, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related