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.โ˜•

Discussion (6)

Collapse
lukeshiru profile image
LUKESHIRU • Edited on

For those wondering how the try/catch example looks without async/await, and just using promises:

const asyncTask = () =>
    new Promise((_resolve, reject) =>
        setTimeout(() => reject("Something not working!"), 1e3)
    );

const foo = () =>
    asyncTask()
        .then(console.log)
        .catch(console.error)
        .finally(() => console.log("After calling AsyncTask"));

foo();
Enter fullscreen mode Exit fullscreen mode

I also used console.error instead of console.log for the error.

Cheers!

Collapse
nehal_mahida profile image
Nehal Mahida Author

Hey mate, Thanks for additional info ๐Ÿค—

Happy Coding

Collapse
yonatanaduk profile image
yonatanaduk

Tnx! I like it ๐Ÿ‘๐Ÿ‘

Collapse
nehal_mahida profile image
Nehal Mahida Author

Your Welcome ๐Ÿค—

Collapse
ravitejanunna profile image
Ravi teja Chowdary

Good Article

Collapse
nehal_mahida profile image
Nehal Mahida Author

I'm glad you like it ๐Ÿค—