DEV Community

Cover image for Async/Await with easy to understand examples.
Nehal Mahida
Nehal Mahida

Posted on • Updated on

Async/Await with easy to understand examples.

Let's first understand the Async keyword.

Put this keyword before the function which returns a promise or which does an asynchronous task.

const foo = async () => {
  return 'done';
}

foo().then((res) => console.log(res));

// done
Enter fullscreen mode Exit fullscreen mode

If you think your function will run asynchronously (fetching data from API) then use the async keyword before that function.

Now there is another keyword Await that works only inside async functions.

(There is a concept of top-level await in which await keyword can be used outside of the async function.)

The Await keyword simply means it makes JavaScript wait until the task is completed.

const asyncTask =  () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('done');
    }, 1000);
  });
}

const foo = async () => {
  const res = await asyncTask();
  console.log(res);
}

console.log('Before Foo Call');
foo();
console.log('After Foo Call');
Enter fullscreen mode Exit fullscreen mode

In the above example, I am creating a dummy function that takes one second to return its result.

There is another function foo that calls asyncTask (with await keyword) and prints the result.

I have put two logs, one is before calling foo and the second is after calling foo.

What do you think will be the output? 🤔

As you may know, whenever JavaScript encounter with await keyword it stops the execution of the current function and put it into the callback queue and start executing the next statement which is the second console log.

Here is an output of the above code.

Before Foo Call
After Foo Call
done
Enter fullscreen mode Exit fullscreen mode
Handling errors while using async/await

In the above example, our promise resolves normally and we are printing the result on the console.

But in case of rejection, it will throw an error so we should handle errors while working with promises.

Using try/catch block.

const asyncTask =  () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      reject('Something not working!');
    }, 1000);
  });
}

const foo = async () => {
  try {
    const res = await asyncTask();
    console.log(res);
  } catch (err) {
    console.log(err);
  }
  console.log('After calling AsyncTask');
}

foo();
Enter fullscreen mode Exit fullscreen mode

Now, If our asyncTask function throws an error control will go into catch block and simply prints the error message then it will start to execute the next statements.

Output

Something not working!
After calling AsyncTask
Enter fullscreen mode Exit fullscreen mode

Very clean. Isn't it?

Now, try to use async/await instead of then/catch in your next project.

If you like this article like, share and mark 🔖 this article!

🏃‍♂️ You can follow me on 👇

🕊 Twitter : https://twitter.com/nehal_mahida

👨‍💻 Github: https://github.com/NehalMahida

Support 🤗

If you are enjoying my articles, consider supporting me with a coffee.☕

Top comments (5)

Collapse
 
yonatanaduk profile image
yonatanaduk

Tnx! I like it 👍👍

Collapse
 
nehal_mahida profile image
Nehal Mahida

Your Welcome 🤗

Collapse
 
ravitejanunna profile image
Ravi teja Chowdary

Good Article

Collapse
 
nehal_mahida profile image
Nehal Mahida

I'm glad you like it 🤗

Collapse
 
nehal_mahida profile image
Nehal Mahida

Hey mate, Thanks for additional info 🤗

Happy Coding