DEV Community

Cover image for The Async Series: Async Functions
Nicholas Mendez
Nicholas Mendez

Posted on • Originally published at

The Async Series: Async Functions

The long awaited async function

In the last post, we covered promises and promise chaining with .then(). Promise chains provided an improvement over nested callbacks but in this post we'll cover something that does even better.

A Recap

Recall our favourite async library lib from previous posts in this series. We saw how we can use the .then() method on promises to form a promise chain.

Enter fullscreen mode Exit fullscreen mode

The promise chain synchronises the async calls so that they execute in the intended order.



However, ECMAscript 2016 released the Async/Await syntax, it allows us to declare async functions. In async functions we can use the await keyword. Await lets us block asynchronous promised based calls and get the value that the promise resolves to instead of using .then(). The following is previous code snippet converted to an async function.

async function printFun(){
      await printBlue("Blue");
      await printGreen("Green");//doesn't execute until printBlue finishes
      await printRed("Red");//doesn't execute until printGreen finishes
Enter fullscreen mode Exit fullscreen mode

Notice we use a top level try catch block instead of the .catch() method. Async functions lets uses easily synchronize promised based APIs in the top level.

It all adds up

Let's see how we can use this with the async add() function.

async function  addAll(a, b, c, d, e, f){
   let res = await add(a, b);
   res = await add(res, c);
   res = await add(res, d);
   res = await add(res, e);
   res = await add(res, f);
   return res;  

Enter fullscreen mode Exit fullscreen mode

The one thing to note however, is that Anything returned by an async function will be wrapped in a promise. So if we wanted to log the result of the last function we would have to do the following.

//call .then() on the promise
addAll(6, 2, 42, 11, 20, -1)

// OR use another async function

async function printSum(){
  let res = await addAll(6, 2, 42, 11, 20, -1);


Enter fullscreen mode Exit fullscreen mode


An that's it for the async series. Async functions really makes things easier to work with async calls but just remember they return promises. I hope this series helped you get to grips with async code in JavaScipt. As always here is a REPL to try out the examples yourself.

Discussion (0)