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.
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:
- It does not undermine the current thread,
- It doesn’t cost much in the CPU compared with promise chaining,
- It helps you write code as though it was synchronous,
- It replaces the crowd of each execution context created by promise chaining with
Things that need to be known about async/await:
- Async/await always returns a promise, i.e. you can use the methods of Promise like
- The use of await alone will produce a syntax error. Therefore, use await inside of the async function,
- Error handling is usually executed with
I think I covered most of the initial stuff regarding the async/await functions.