Home Courses Await Explained - Promises Made Easy

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:

  1. You must use async before the function
  2. await can only be used inside an async function
  3. 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

  1. First, loginPromise resolves after 2 seconds
  2. Then, tokenPromise resolves after 3 seconds
  3. Finally, both results are printed together


Key Points

  1. Async/await makes code simple and clean
  2. No need to use .then() again and again
  3. Works well for handling promises
  4. If one promise takes more time, the result will come after that


Share this lesson: