Promises or Async/Await? A Simple Explanation

If you’re new to JavaScript, you may have heard that async/await is “syntactical sugar to make promises easier to work with.” That’s kind of like saying that spaghetti and meatballs is a great meal, but parmesan makes it yummier. Well, except for the lactose intolerant and vegans.

Let's start with Promises. Promises are placeholders in your code for tasks that will be completed later, a.k.a.“asynchronous” tasks.

Let’s review an example of a promise with error handling. In this example, we will create a little program that greets anyone named “Dan” as such, while people who are not named Dan are greeted as “Not-Dan.”

Promises.JPG

As I mentioned, async/await is like “syntactic sugar” for promises. Simply stated, that means it makes promises easier to read and use -- particularly when you have multiple .then() statements in your code.

Just as sugar coats a piece of cereal, an asynchronous async/await function wraps around your code. Let’s write a similar “Dan” function that utilizes async/await to see the difference.

AsyncAwait.JPG

In terms of error handling, that is done a bit differently with async/await. Since there is no .then(), instead we place the code we want to try running in a .try() block and follow that with .catch() to catch errors. Here’s the code displaying the error message “Hello Not-Dan, what’s up?” which is the alternative text we specified on line 48:

asyncawaitNotDan.JPG

I hope this helps some novice coders better understand promises and how async/await can help simplify the code when there are multiple .then() statements by using one asynchronous callback function instead.