JavaScript Async Await. A Better Way To Handle Asynchronous Code.

Lexical Magazine
LexicalMagazine
Published in
3 min readOct 4, 2020

Async await is the newest way of managing asynchronous operations in JavaScript. We already have promises to do that so why introduce another way of handling asynchronous code? Although promises work well and are a great improvement over using callbacks they are not very readable and intuitive to use.

Async/Await is just syntactic sugar over promises but it makes async code look synchronous and thus much easier to follow and reason about.

How do you use Async/Await?

In order to make use of the async/await API you have to make the function asynchronous by declaring it prefixed with the async keyword which tells JavaScript that you intend to use the await keyword in that function. Trying to use await in a normal function will just throw an error.

In order to make it easier to understand what the async keyword does to a function lets first take a look at how a normal function behaves in terms of its return value.

const nonAsyncFunction = () => {
return 5;
};
const res = nonAsyncFunction();console.log(res); // 5

When we run a normal function and store the result in the res variable we can see that the value is indeed the actual return value of the function which in this case is 5.

Now let’s take a look at the asynchronous version of the same function by prefixing it with the async keyword.

const asyncFunction = async function() {
return 5;
};
const res = asyncFunction();console.log(res); // Promise { 5 }

This time when we log the res variable we can see that it’s not the return value of the function but instead it’s a promise with the return value as its resolved value. The promise already has the value because we are returning the value right away. We can get the actual return value of the async function by calling the then method of the promise returned from it.

asyncFunction().then((val) => console.log(val)); // 5

But what’s the benefit of doing this? Doing this now allows us to use await inside the function. Await tells JavaScript to pause running your code until the operation you are waiting on completes. Let’s take a look at an example.

const fetchResource = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('success');
}, 5000);
});
};
const asyncFunction = async () => {
const res = await fetchResource();
console.log(res); // success
};
asyncFunction(); // success is logged to the console after 5 sec.

In the example above we simulate an operation that takes about 5 seconds to finish using the fetchResource function. In our async function we use the await keyword to tell JavaScript to pause running our code until the fetchResource function returns a value.

As you can see this is more intuitive and more readable because the code looks synchronous and is run one line after the other. Also note that this only pauses your code and other code running will continue to run as normal.

You are not limited to just a single use of the await keyword in a function and this is where the true power of async/await lies.

const asyncFunction = async () => {
const res = await fetchResource();
const res2 = await fetchResource2(res2);
const res3 = await fetchResource3(res, res2);

// run the rest of the function.
};

As you can see we can write our code to look like it’s synchronous and use the result of one asynchronous operation in the next one. This is much easier to read and keep track of what’s happening.

How do you handle errors when using async/await?

We can add a try catch block inside the function to catch any errors that are thrown and handle them in the catch block.

const asyncFunction = async () => {
try {
const res = await fetchResource();
if(res.error) {
throw new Error('The was an error fetching the resource')
} else {
// Run the rest of the function
}
} catch (e) {
// handle any errors here.
console.log(e);
}
};

Conclusion

As you can see, although async/await uses promises underneath it improves on promises by making our code more readable and easier to follow.

Thanks for reading and please leave a comment below if you have any questions and I’ll reply as soon as I can.

--

--

Lexical Magazine
LexicalMagazine

Lexical is a software development media company sharing the knowledge and wisdom we have acquired over the years with the community.