Promises and Async/Await
Asynchronous operations in JavaScript can be handled in several ways. Promises and async/await are modern features that make working with asynchronous code much easier and more readable than traditional callbacks.
Promises
A Promise is an object representing the eventual completion or failure of an asynchronous operation. A promise can be in one of three states:
- pending: The initial state; neither fulfilled nor rejected.
- fulfilled: The operation completed successfully.
- rejected: The operation failed.
You can create a new promise using the Promise constructor:
const myPromise = new Promise((resolve, reject) => {
// Asynchronous operation here
setTimeout(() => {
const success = true;
if (success) {
resolve('The operation was successful!');
} else {
reject('The operation failed.');
}
}, 1000);
});
You can then use the .then() method to handle the fulfilled case and the .catch() method to handle the rejected case.
myPromise
.then(result => {
console.log(result); // "The operation was successful!"
})
.catch(error => {
console.error(error); // "The operation failed."
});
Async/Await
async/await is syntactic sugar on top of promises that makes asynchronous code look and behave more like synchronous code.
async: Theasynckeyword is used to declare an async function. Async functions always return a promise.await: Theawaitkeyword can only be used inside an async function. It pauses the execution of the function until the promise is fulfilled or rejected.
Here is the same example from above, but using async/await:
async function myAsyncFunction() {
try {
const result = await myPromise;
console.log(result);
} catch (error) {
console.error(error);
}
}
myAsyncFunction();
async/await makes asynchronous code much easier to read and write, especially when dealing with multiple asynchronous operations in a sequence.