Asynchronous JavaScript: How to use async and await

Let’s look at some new syntax introduced as a part of ES2017 to help organize code around promises. In many cases, this new syntax — namely the async and await keywords — will help you write more readable and maintainable asynchronous code, but it’s not without its drawbacks. We’ll first look at how async and await can be used and then talk about some of the downstream implications of using it.

To start, we’ll lay out a simple example using promises and then refactor it to use async/await. In our example, we’ll use axios, a promise-based HTTP library.

Our code above defines a function that takes a user ID and returns a promise (the return type of axios.get().then().catch()). It calls an HTTP endpoint to get profile information and will resolve with a profile or reject with an error. This works fine, but there is a lot of syntax inside getUserProfile that clutters our actual business logic:

serverpoint hosting banner

You might also like More from author

Leave A Reply

Your email address will not be published.