DEV Community

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

Posted on • Originally published at thecodecrusade.wordpress.com

3

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.


    printBlue("Blue")
    .then(()=>printGreen("Green"))
    .then(()=>printRed("Red"))
        .catch(err=>console.log(err));
Enter fullscreen mode Exit fullscreen mode

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

image

Async/Await

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(){
    try{
      await printBlue("Blue");
      await printGreen("Green");//doesn't execute until printBlue finishes
      await printRed("Red");//doesn't execute until printGreen finishes
    }catch(e){
      console.log(e);
    }    
}
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)
  .then(function(res){
    console.log(res); 
  });

// OR use another async function

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

printSum();

Enter fullscreen mode Exit fullscreen mode

Conclusion

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.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay