Easing pain of asynchronous programming

Actually, programming in Node.js is painless as long as you keep things simple, limited to one layer of async/await. Things get complicated when you have deeper structures, using at the same time modules with async/await functionality. In general it is better to stick to one or maximum two levels of callback. If you need more, it means, that maybe you should refactor your code. Below I described two things I found useful in avoiding too many async/await levels.

  • IF – check if you can drop one await/async by refactoring code with IF statement. In async code almost nothing stops execution, except things like IF statement.
  • JOIN – often mess with multilevel async/await is because you expect to get some data, but instead you get only promise. If the data is related to a database source, try to refactor your database SQL queries usingĀ  JOIN statement. This way, maybe, you can get the missing piece of data in one callback, instead two separate callbacks related to two separate SELECT queries. JOIN queries are more complex than simple SELECT ones, but even JOIN queries are less complex than messing with three or more levels of callback functionality in async code.