Async/await – how it works

Async/await – how it works

Async/await – how it works

Async/await is a brand new way of handling asynchronous calls in JavaScript. If you don’t know how it works, in this article I will be providing some examples to help you get started.

Async/await – how it works

JavaScript async/await is a relatively new way to handle asynchronous operations in JavaScript. It gives you power new to make your code shorter and more understandable.

Before async/await, callbacks and promises were used to handle asynchronous calls in JavaScript. Everyone who learns JavaScript has heard about the so-called callback hell.  However, I won’t be writing about this because callbacks aren’t the main focus of this post.

Promises for beginners

https://gist.github.com/Xedii/2937c3a21363585e835c39bbec376b83
https://gist.github.com/Xedii/b2420c2b4e2b519d7186040b0d448df5

As you can see in the example above, I need to make a requestMock function on the stub to call an asynchronous operation. It’s a perfect example of using setTimeout to make a long-running process asynchronous operation.

The promise object – which is returned fromrequestMock – uses the then method. This method gives you the possibility to handle the asynchronous execution, in the case that requestMock ends successfully.

It’s worth mentioning that the promise uses not only thethen method but also the catch method. Thecatch the method enables you to handle asynchronous operations that end unsuccessfully.

You will need to use requestMock() with the `then` method to handle with your asynchronous operations.

Rewrite a promise to Async/Await

https://gist.github.com/Xedii/0ac00b27c198fead18c150181dc67352

As you can see, in the example above I have used the async keyword which means that this function is asynchronous and returns the promise. Whenever you use async/await, make sure you’re using the try/catch statement to handle errors.

You should also use await to wait for the end of requestMock and declare res to save the returned value. ‘Await’ must be called inside async. Withoutawait, the asynchronous function will end and it will not wait for the result of the asynchronous function.

Key points to keep in mind

  • Both async/await and the promise play the same role, but in the first case, use the `then` syntax, whereas in the second case use the async/await syntax.
  • Async/await is more readable and more comfortable to write.
  • Async/await is – like promise – non-blocking.
  • When you decide to use async/await, it’s good practice to use tryCatch to handle errors. With promise, you have to use only catch to handle an error.
  • Be careful! It’s easy to get lost with a promise if you have a lot of nesting (6 levels) bracers and the statements are returned. With async/await you won’t have this problem.

When you declare async, you can use the await keyword to make your code in a synchronous fashion. The code will look very similar to its synchronous counterpart, but it will still be asynchronous.

However, the important fact is that you will still need promises to write asynchronous code.

Async/await with promises

As I have already mentioned, an async function returns a promise. So you can write something like this:

https://gist.github.com/Xedii/5c0c8e5e39d79e26f399a20fb658aa0d

Therefore, you can combine the promise.all and async/await to make a lot of many requests:

https://gist.github.com/Xedii/6d528d4d6ca059a639aeea08902c71e0

Let’s imagine that you have to limit asynchronous operations in time. I usually use the async library to do it. One of the functions in this library is mapLimit.

MapLimit gives you the opportunity to carry out asynchronous operations if you want to do some operations at the same time but not all of them at once.

https://gist.github.com/Xedii/9c6f6ea4171a171f42d910a85d936388

In the example above, you can see a standard request function to stub the long background process. At this stage, you can create the mapLimit function. In the mapLimit function, you can slice up an array of functions into a chunk array. Subsequently, you can use the for-of loop which was added in ES6 to access the elements of the array.

In the loop, it’s helpful to use await Promise.all because you want to process the requests concurrently. This is possible because, at the beginning of the function, the main array is divided into arrays of chunk functions.

Congratulations! You now have the generic mapLimit function. You can use it every time you have to process anything or something concurrently!

How to implement async/await with streams?

Node.js 10 was released on April 24, 2018. The publication of  Node.js 10 was a kind of breakthrough because this version allows you to use async/await, when you operate on streams.

It’s also worth mentioning that the ES2018 version allows the possibility to carry out an asynchronous iteration.

Usually, your streams look like this:

https://gist.github.com/Xedii/0df3ad9bb763b5acc93eef5f46dee301

Node.js 10 gives you the possibility to use an asynchronous iteration to read a file asynchronously. You can iterate streams only if you declare async ahead of the function. More examples can be found on this page: 2ality.com

https://gist.github.com/Xedii/7cdd48f30fdf72c400e149734c550c58

You see? Everything is understandable and readable. In this example, I used the for-await-of loop to iterate. This operation is possible thanks to the Symbol.asyncIterator

To start,  let’s take a look at Symbol.iterator

`Async Iterators `are similar to regular iterators in that they implement 3 methods: the next method moves to the next item (the rest of the bullet list) and eventually a return or a throw method.

There are some differences between an `async iterator` and a conventional `iterator`. Instead of returning a plain object { value, done }, an async iterator returns a promise which is the counterpart of { value, done }.

Similarly, an async iterable is an object with a Symbol.asyncIterator function that returns an asynchronous iterator. It enables you to change the syntax of `for…of` into an asynchronous for await...of 

These are already implemented in recent versions of Node.js, and you can apply them by using the --harmony-async-iteration flag.

Conclusion

You can write code both in a synchronous fashion and intuitively way.

async/await is a syntax that was added in  ES8 (ECMAScript 2017) of the JavaScript version. It’s supported by all modern browsers. Node.js programmers can use this syntax from the Node.js 8 version.

As you can see, the async/await the syntax is not at all complicated. It’s just another way of working with the promise object, and thanks to this you’re now able to write code much more synchronously and intuitively fashion.

It’s also important to remember that the ‘Async’ function returns a promise but ‘await’  can only be used inside the async block.

See also

Download e-book:

Scalac Case Study Book

Download now

Authors

Michał Mrotek

I have been fascinated with JavaScript for a few years. I have already made an application that aggregates the best deals from the most popular, Chinese online-shops. The purpose of my second mobile application is to collect the opinions of people about the latest news. I am excited to broaden my knowledge and explore new things. I was in charge of creating a recruitment platform. Moreover, I was part of the team that created the platform for lawyers. Besides the IT-world, I am interested in tech trends. I am also an enthusiast of card manipulation.

Latest Blogposts

17.04.2024 / By  Michał Szajkowski

Mocking Libraries can be your doom

Test Automations

Test automation is great. Nowadays, it’s become a crucial part of basically any software development process. And at the unit test level it is often a necessity to mimic a foreign service or other dependencies you want to isolate from. So in such a case, using a mock library should be an obvious choice that […]

04.04.2024 / By  Aleksander Rainko

Scala 3 Data Transformation Library: ducktape 0.2.0.

Scala 3 Data Transformation Library: Ducktape 2.0

Introduction: Is ducktape still all duct tape under the hood? Or, why are macros so cool that I’m basically rewriting it for the third time? Before I go off talking about the insides of the library, let’s first touch base on what ducktape actually is, its Github page describes it as this: Automatic and customizable […]

28.03.2024 / By  Matylda Kamińska

Scalendar April 2024

scala conferences april 2024

Event-driven Newsletter Another month full of packed events, not only around Scala conferences in April 2024 but also Frontend Development, and Software Architecture—all set to give you a treasure trove of learning and networking opportunities. There’re online and real-world events that you can join in order to meet colleagues and experts from all over the […]

software product development

Need a successful project?

Estimate project