Simple Refactoring Tips While Handling Async Requests

Mukul Chaware
Mar 30 · 2 min read

While writing code, there are many instances where we have to use APIs, HTTP requests and other types of asynchronous methods. There is one small refactoring method I like to use when handling async requests that takes the same amount of time to write but helps to make your code more readable, testable and modular.

For example, consider a simple case in which our objective is to fetch usersdata, do some manipulation over the results, and then return that result.

The above code is simple, readable, and straightforward. Even though the above code works perfectly and we get our desired result, there are still a few small issues we might face as the codebase grows in size.

  1. Functions or methods should follow the ‘Single Responsibility Principle’ (SRP) which states that ‘every module, class, or function should have responsibility for a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class.’ In the above case, the above function is fetching data AND applying some changes over it.
  2. It is difficult to write tests for it. Mocking and stubbing functions is relatively easier than mocking HTTP or asynchronous library methods.
  3. Error handling is not handled ‘elegantly’. For example, if we have to fetch usersin multiple places for different purposes, then we will have to fetch data and write a catch statement every time to handle that.

Instead, if we make a slight modification in the way we write this code, all of these issues can be solved fairly easily.

The functions now follow (SRP). It also helps in following the DRY (Don’t Repeat Yourself) principle. The above functions are now testable and we can also write tests for the asynchronous requests and data manipulation separately. The error is handled at the source now, which gives us more control over the response. For example, we can return a mock response that contains an error message when the ‘axios’ request fails.

It’s the little things that matter the most. Code refactoring plays a very important role as your codebase grows in size.

Hopefully this helps some of you on your journey to writing more sustainable code. This is my first ever blog here at Map My Customers. After procrastinating and hesitating for quite some time, I am finally here! I’m looking forward to learning, growing, and writing as much as I can :)

Thanks for reading.

If you like the sound of working on large-scale data visualization, deep geo-analytics, and cutting edge technology, feel free to drop by the careers page of Map My Customers. We’re always looking for more comrades :)

Map My Customers Engineering & Design

Creative engineers and designers building the future of productivity in the field.

Mukul Chaware

Written by

Map My Customers Engineering & Design

Creative engineers and designers building the future of productivity in the field.