Async & Await Keywords
By: Charles Tillmon

Async & Await Keywords

When ES2017 was released along with it came the async and await keywords. These keywords were developed to make working with promises easier or what is referred to as syntactic sugar. When used theses help your asynchronous code look like traditional synchronous code structure and will help minimize the chaining needed to complete task. In theory this should make your code easier to digest. To be clear these keywords do not replace promises but are supplemental to make your code more efficient.

The async keyword can be pre-fixed to a function declaration to define it contains asynchronous code. These functions will always return a promise as a result. Inside of these async defined functions you will see the use of the await keyword. The await keyword will pause the execution of an async function until a resolved value is returned. This pausing of execution will not cause blocking behavior because the event loop is free to perform other tasks. This means that you will still be able to interact with other parts of the application.

Another noticeable difference will be experienced with error handling. These keywords are typically associated with try catch blocks to catch errors over various lines of code. The alternative would be chaining a catch method to each individual line of code, which as you can expect would get messy very quickly. However, like we always mention this should not be treated as a one solution solves all approach. Understanding these concepts and the underlying promises they represent will help in knowing how to properly implement these tools. 

要查看或添加评论,请登录

社区洞察

其他会员也浏览了