Using Async/Await with Axios

Mehmet Eyüpoğlu
Oct 15, 2020 · 2 min read

Writing a legible code has always been a developer’s ultimate goal. Therefore, looking for optimizations or refactoring in our code should be one of the core skills that we have to gain in time.

Image for post
Image for post

Recent experience in one of the projects that I have been developing showed how important it is to seek better solutions to our existing code. Imagine a scenario in which you send some data to the server and wait for an id to send another piece of data. This is usually the case if you are dealing with sending data in a few steps.

In this article, you will see how I sent the data with the Axios library and used it inside an async/await structure and the benefits of async/await.

Without async/await, there are a few ways to achieve our scenario. You just wait for an answer in the aftermath of an Axios promise, for instance, and put another one inside the previous one as in the example below:

Conducting asynchronous operations with promise chaining undermines our desire to write readable code. Therefore, a cheaper, more effective, and prettier version of the same code could be achieved with async/await:

Async/await is indeed a syntactic sugar, that is, a twist in code that makes it prettier but has no change in the functionality. Using async/await instead of promise chaining is advised for a few good reasons:

  1. It does not undermine the current thread,
  2. It doesn’t cost much in the CPU compared with promise chaining,
  3. It helps you write code as though it was synchronous,
  4. It replaces the crowd of each execution context created by promise chaining with .then(),

Things that need to be known about async/await:

  1. Async/await always returns a promise, i.e. you can use the methods of Promise like .then() ,
  2. The use of await alone will produce a syntax error. Therefore, use await inside of the async function,
  3. Error handling is usually executed with try/catch structure,

I think I covered most of the initial stuff regarding the async/await functions.

Dünyada 10 Çeşit İnsan Vardır. Binary Bilen ve Bilmeyen.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store