Understanding of NodeJS Async functions

Having a good understanding of NodeJS Async functions is key to writing basic NodeJS applications. This post is my understanding of asynchronous functions while using NodeJS. This is not a starter tutorial But talks about some best practices and tips for writing some code. One of those reflections of my learnings

MYTHS of NODEJS ASYNC

First, let us kill all the myth surrounding NodeJS Async functions.

  1. NodeJS is NOT Async by nature. Its single threaded and hence mandates (in almost all cases) to write async code. Its programmer’s responsibility (and is of architect’s as well) to ensure the code is async.
  2. Writing a code using a callback function, need NOT always be asynchronous.
  3. V8 engine (or in some case Chakra) is NOT responsible async capabilities. It is the powerful libUV, that enables this capability.

Those myths, thrown over the head, let us look at the three different ways of writing async functions.

  1. First one is using the traditional popular callback. Callbacks are like the traditional manager, who loves micromanaging. So give careful consideration to everything you write to ensure that it is async.
  2. Then comes the cool kid called “promise“. Promises are cool, that it is really cool. It brings things like pipes and chaining from the cool posix world.
  3. Finally the new kid “async – await“. This feature tries to be like the Che Guevara of node world. It wants the async aspects affordable (mentally) to everybody. It has mixed reactions from the dev community. For LTS versions of Node, one might need to use the ‘–harmony’ flag. (As of writing this post).

CALLBACKS

If you are writing callbacks, please use the following best practices.

  1. Always use “err” as the first argument. (Unless you have an alternative better reason for not doing this)
  2. Always use “data” as the second argument.

PROMISES

If you are writing promises, please consider the following

  1. It is best to use both promises and call back function for whatever functions you write. This helps the traditional folks to continue using callbacks.
  2. Promises are cool, as it helps handle errors and non-error cases separately.
  3. If using promises and call back together, use the following way for errors

reject err; return cb(null);
  1. For success, cases follow

resolve(data); return cb (null, data); 

ASYNC-AWAIT

In case of async-await, there is only one point, if I will make at the moment.

That’s it for the day.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.