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.
- 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.
- Writing a code using a callback function, need NOT always be asynchronous.
Those myths, thrown over the head, let us look at the three different ways of writing async functions.
- 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.
- 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.
- 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.
- Always use “err” as the first argument. (Unless you have an alternative better reason for not doing this)
- Always use “data” as the second argument.
PROMISES
If you are writing promises, please consider the following
- 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.
- Promises are cool, as it helps handle errors and non-error cases separately.
If using promises and call back together, use the following way for errors
reject err; return cb(null);
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.
- If you are, too used to the functional pattern of coding, better avoid this.
That’s it for the day.