Promises
Promises are a way to handle asynchronous operations in JavaScript, providing a cleaner alternative to callback functions. A Promise represents a value that may be available now, in the future, or never.
Key Characteristics of Promises:
- States: A Promise can be in one of three states:
- Pending: Initial state, neither fulfilled nor rejected.
- Fulfilled: Operation completed successfully.
- Rejected: Operation failed.
- Methods:
- then(): Executes when the Promise is fulfilled.
- catch(): Executes when the Promise is rejected.
- finally(): Executes regardless of the Promise’s outcome.
Error Handling of Promises: To handle a resolved promise, use the .then() method, and for a rejected promise, use .catch(). To execute code after promise handling, use .finally(), ensuring the code within runs regardless of the promise state.
Example: During database server data retrieval, a Promise remains pending until successful data reception (resolved state) or unsuccessful retrieval (rejected state).
const promise = new Promise(function (resolve, reject) {
const string1 = "w3wiki";
const string2 = "w3wiki";
if (string1 === string2) {
resolve();
} else {
reject();
}
});
promise
.then(function () {
console.log("Promise resolved successfully");
})
.catch(function () {
console.log("Promise is rejected");
});
Output:
Promise resolved successfully
Difference between Promise and async/await in Node
Promises use .then()
and .catch()
for handling asynchronous operations and chaining, while async/await
provides a more readable, synchronous-like syntax for managing asynchronous code with try/catch
for error handling.
Asynchronous programming is fundamental in Node.js, ensuring non-blocking operations. Promises and async/await are two key techniques for managing asynchronous code, each with distinct syntax. This article explores their syntax differences and helps you choose the best approach for your projects.
Table of Content
- Promises
- Async/Await
- Difference Between Promise and Async/Await
Contact Us