Using Async/Await with Axios

Mehmet Eyüpoğlu
SDTR
Published in
2 min readOct 15, 2020

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.

Source: https://www.freepik.com/vectors/design

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.

--

--