Await Explained - Promises Made Easy
Async/await is an advanced way to handle promises.
Earlier, we used the .then() method to resolve promises, but async/await is a simpler and cleaner approach.
You don’t need to use callbacks here, and you can easily get the data outside the promise.
Creating a Promise
First, we create a simple promise:
const loginPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ login: true, name: 'anil sidhu' });
}, 2000);
});
This promise resolves after 2 seconds and returns an object.
Handling Promise using .then()
Earlier, we handled promises like this:
loginPromise.then((result) => {
console.log(result);
});
After 2 seconds, the result is printed.
Using Async/Await
Now we handle the same promise using async/await:
async function handleLoginPromise() {
const result = await loginPromise;
console.log(result);
}
handleLoginPromise();
Important points:
- You must use
asyncbefore the function awaitcan only be used inside an async function- It waits for the promise to resolve and then gives the result
Multiple Promises Example
Now we create another promise:
const tokenPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ token: 'sdhcskd232379230293927393' });
}, 3000);
});
Now handle both promises:
async function handleLoginPromise() {
const result = await loginPromise;
const tokenResult = await tokenPromise;
console.log(result, tokenResult);
}
handleLoginPromise();
How it Works
- First,
loginPromiseresolves after 2 seconds - Then,
tokenPromiseresolves after 3 seconds - Finally, both results are printed together
Key Points
- Async/await makes code simple and clean
- No need to use
.then()again and again - Works well for handling promises
- If one promise takes more time, the result will come after that