Promises, Async/Await
Expert-Level Explanation
Promises and Async/Await in JavaScript are tools for handling asynchronous operations. A promise is an object representing the eventual completion or failure of an asynchronous operation. Async/Await is syntactic sugar built on top of Promises, making asynchronous code easier to write and read.
Creative Explanation
A promise is like a food delivery order. When you place an order (create a promise), you're given a tracking status (pending). When the food arrives (the promise is fulfilled), you enjoy your meal (resolved). If there's an issue and your order can't be delivered (rejected), you handle it differently. Async/Await is like having a personal assistant who handles the details of tracking your order, making the process more straightforward.
Practical Explanation with Code
// Using Promises
const checkWeather = new Promise((resolve, reject) => {
let weather = 'sunny';
if (weather === 'sunny') {
resolve('Weather is sunny');
} else {
reject('Weather is rainy');
}
});
checkWeather
.then(message => console.log(message))
.catch(error => console.log(error));
// Using Async/Await
async function getWeather() {
try {
let message = await checkWeather;
console.log(message);
} catch (error) {
console.log(error);
}
}
getWeather();
Real-world Example
Imagine you're waiting for a friend to confirm a weekend plan. The promise is the friend's response. You go about your day (and other tasks) while waiting for the response. Once you receive it (the promise is resolved or rejected), you make further plans.