Refactor a React action creator using AsyncAwait syntax

As soon as I learned about the AsyncAwait syntax in ES6 and ES7, I soon realized that this is going to be the end of Javascript promises as we know it. There are tons of articles explaining how they work and why they are great.

This little blogpost is solely to demonstrate how I refactored a standard action creator that uses an async call through Axios, using async/await.

This is the vanilla action creator:
... and this is the end result:
... and of course, goes without saying, if I want to further abuse this new syntax I can further compact it as follows!!!
The rules I follow to refactor are as follows:
  1. Refactor the arrow functions and remove any noise. In this case I removed the function keyword, the extra braces and the brackets from the dispatch argument.
  2. Identify the function that contains the async function and prefix it with 'async' keyword. In this case, the async function (axios) is contained in the dispatch arrow function.
  3. Identify the async function and prefix it with 'await' keyword. In this case, it is the axios function.
  4. Store any intermediary responses from promises and such, in a constant, in order to get rid of the 'then' keyword.
Post a Comment