Promises or Async/Await? A Simple Explanation
2 min read
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.”
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.
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:
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.