DEV Community

Cover image for Waiting on a Promise.. Async and Await in JavaScript
Quinn Sissler
Quinn Sissler

Posted on

Waiting on a Promise.. Async and Await in JavaScript

Why use Async and Await?

By default, Javascript runs synchronously. This means each operation will wait to run until the previous operation is completed. For example, running these two lines of code:

Console-logging "Hello" and "World"
will always result in this output in the console:
Hello World
Line 1 is run first and Line 2 follows.

However, sometimes we need our code to run asynchronously. Enter: async and await!

Async and Await

Async and await are used with promises. Placing the async keyword before a function ensures that function will return a promise. The await keyword can only be used inside an async function. Anything after the await keyword tells Javascript to wait until the promise resolves and returns its results. So when may we want to use async and await?

Putting it in Practice

While completing our capstone projects for bootcamp, I was helping a friend brainstorm some possible ways for her app to function. She wanted a user to click on a dog they were interested in adopting and then fill out an adoption form. We decided to have the initial click event create a post request, essentially joining her user and the adoptable pup and then push the user to another page where they could input more information. However, her post function would push the user to the form page before the promise resolved, meaning we did not have the id for the newly created donation form yet and therefore could not use that id in our url and then again in our future patch request once the user completed their form. To solve this issue, we were introduced to async and await!

First, we added the async keyword to our function. We set our fetch to a constant (res) and added the await keyword in front of the fetch. We then declared a new constant (data) and set that to our res.json(), including the await keyword once more. The await keyword tell JavaScript not to continue on to the next operation until the prior operation is resolved.

We then created a function aptly named redirect that pushes the user to the page where they can update the rest of the form information. Lastly, we invoke the redirect function using the data we received from our promise after it is parsed to json.

Our final code:

Async and Await Code

Conclusion

In conclusion, async and await is a great tool to use when the need arises for JavaScript code to be able to run asynchronously. While today we saw just one great example of using async and await, there are many other ways it can be utilized, which I look forward to using in the future.

Top comments (0)