Alex Moline

Feb 14, 2021

3 min read

Async/Await

Schrodinger’s Cat

As programmers, it is necessary to always improve the way we code and how we make our code easier to be read by other programmers. The concepts used today may inevitably change and it is important to keep up. One change that is becoming more and more popular are async/await functions. These functions are slowly overtaking the traditional uses of promise-chaining and are doing so in a way that is very easy to be read and programmed.

So, what are async/await functions? Basically they are just functions that make use of the async and await keywords and return a promise, which is an object. The async keyword means that the following function will be asynchronous. For a function to be asynchronous means that all the code will be ran regardless of resource availability as opposed to synchronous code which executes code when the necessary resources are available. By putting aysnc in front of the function we allow promise-based behavior to be written in a cleaner style. Just like promises, aync/await functions return a promise that will be resolved with the value from the async function or it will be rejected with an error. The use of the await keyword is to suspend execution of code past the await keyword until the returned promise is either rejected or fulfilled. A good way to look at it is like Schrodinger’s cat, where the cat is the action of the await, a Schrodinger’s promise if you will, of the action either being resolved thus running the await code or being rejected and throwing an error.

Now, time for some code! Here we have some psuedocode of a promise chain and an asynchronous version of that code.

Promise Chaining

Notice how the async await version is much easier to read and understand as it waits for the result of fetch. Regarding the try and catch statements on the async function, they work like the response and reject. Try is what you want to happen in the event that the response from the

Async Await

promise is a positive one, whereas catch is the rejection of the promise and literally catches the error! The cleaniness of the async function is a huge advantage when compared to promise chaining which can be disorganized and difficult to read.

Overall, the option to use async await over a normal promise is a personal prefrence, however it does come with benefits that can not be rejected such as it generally cleaner form and overall lack of code when compared to a bunch of then statements that can occur from promise chaining. Lastly is the benefit from code that essentially functions as if it was synchronous. Async functions are one of the best ways to supercharge your code in a new and innovative way!