FeaturedIT topics

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.

let getUserProfile = (userId) => {
return axios.get(`/user/${userId}`)
.then((response) => {
return response.data;
})
.catch((error) => {
// Do something smarter with `error` here
throw new Error(`Could not fetch user profile.`);
});
};
getUserProfile(1)
.then((profile) => {
console.log('We got a profile', profile);
})
.catch((error) => {
console.error('We got an error', error)
});

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:

  .then((response) => {
/* important stuff */
})
.catch((error) => {
/* more important stuff */
});

Related Articles

Back to top button