Published on

Async/Await functions in JavaScript

Ever wondered what those Async/Await keywords you saw in that one JavaScript tutorial mean? Well look no further as this blog post will teach you all about the Async/Await keywords as it pertains to JavaScript

Great diagram contrasting Synchronous vs Asynchronous executions

Figure 1: Great diagram contrasting Synchronous vs Asynchronous executions

What are the Async & Await keywords?

First, let’s go through what the Aysnc/Await keywords actually mean as it relates to JavaScript.

The Async keyword is short for ‘Asynchronous’ and in always positioned before a function. This is done to indicate an Async function and more importantly, that the function being specified as Async will always return a promise.

The body of an Async function can contain zero or more Await keywords. The difference between an Async function with one or more Await keywords and one without any Await keywords is that the non Await function will behave in a synchronous manner while the one containing one or more Await keywords will act in an asynchronous way.

Next, we have the Await keyword. This keyword is only ever syntactically valid inside Async functions and it primarily serves to make JavaScript wait until the promise inside the Async function settles and returns a result. This single keyword is responsible for converting synchronous functions into asynchronous ones, just by the act of allowing other processes to run while awaiting a value from a promise(no pun intended 🙂 ). So note that it only makes the promise containing code block wait, while the rest of the program executes normally.

Let’s go over an example to explain these keywords in greater detail:

async function abc() {

  let newPromise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("Promise is finished!"), 2000)
  });

  let promiseResult = await newPromise;

  alert(promiseResult); // "done!"
}

abc();

Now for an explanation of the above code snippet:

  • The Async function is declared with the Async keyword
  • Inside the abc() function, a Promise instance is created. This promise will resolve in 2 seconds, as indicated by the setTimeout(() => resolve("Promise is finished!"), 2000) line
  • Then the await newPromise line will pause the abc() function’s execution until a return value from the promise declared above it, is obtained. This means that the any line below the await keyword will not be executed while waiting for the promise to resolve. Once it is resolved, the rest of the lines in the abc() function will be executed
  • Note: the rule of pausing the execution on the await keyword only applies to the abc() function and not for the entire program. The rest of the program will execute normally while the abc() function is waiting for a return value from it’s promise
  • After the promise in the abc() function is resolved, the alert(promiseResult) line will display an alert message in the browser

So at this point you might be wonder what a promise is, right? Just keep reading to find out…

What is a JavaScript Promise?

The 3 states of Promises in action

Figure 2: The 3 states of Promises in action

The JavaScript promise represents an object that is used in asynchronous operations to produce a single value some time in the future. Due to their asynchronous nature, promises can only have one of three states at any time, those states being: fulfilled, rejected, or pending.

The fulfilled state represents when the operation is completed successfully, the rejected state for when the operation fails and the pending state to represent the initial state of the promise where it is neither fulfilled nor rejected.

Note that the value returned by a promise is not known at the time of its creation, which is why it can use handlers for getting the success value or failure reason for it’s resulting values.

Lastly, a promise can be labelled as ‘resolved’ when it reaches a state of either ‘fulfilled’ or ‘rejected’ but not ‘pending’.

If you want learn more about promises, just visit the MDN Web Docs’s page on them by clicking here.

Conclusion

Thanks for following along in this article and if you have any questions or concerns please feel free to post a comment in this post and I will get back to you if I have time.

Well that’s all for today, I hope you found this article helpful. Thanks so much for reading my article! Feel free to follow me on Twitter and GitHub, connect with me on LinkedIn and subscribe to my YouTube channel.