JavaScript Async & Await

Introduction

In JavaScript, there are two keywords that are new in es7. These awesome keywords are async and await. They allow developers to write asynchronous code in a synchronous way. Asynchronous code is run independently of the execution order of the program; think of it as a background process. For example, getting a file takes time; you wouldn’t be able to access that file until it’s available, so using it before it’s received would cause an error. Well, async and await are there to solve this issue.

 

Async & Await

Async and await allows code to be written in a synchronous way (one line executing after the other), which is why they must be used together. Now, async changes a function or class method to an async function; this turns the function essentially into a JavaScript promise. Now, a promise is just an easier way to write asynchronous code. It’s an upgrade from callbacks. So, being able to use promises is great, but it’s the¬†await keyword that changes everything.

The await keyword allows you to pause the execution of an async function until the asynchronous code is done executing. It’s like a school bus stop sign telling the program to wait until all the kids pass by. Now, the keyword can only be used in an async function, but it makes dealing with async code easier and increase code cleanliness. Much better than using callbacks. Here’s an example that shows the difference; imagine these functions as server requests.

As you can see the code is more clear and the await keyword pauses the execution until the data is received.In the former, you have to declare a callback just to log that information from the server. Now, imagine if you wanted to get a group of pictures in order; you’d have to write a callback within a callback within a callback. With async and await, you can get them all in the form of an array using Promise.all. So, this is an awesome improvement over the former, so enjoy the shiny new toys.

 

Conclusion

Async and await are great inclusions to the JavaScript language on top of promises. Using these keywords we can stay far away from callbacks and write code that won’t make you go insane. With that said, happy coding!

 

Resources

Async

Await

Promises

Callback

Leave a Reply

Your email address will not be published.