MYTHS of NODEJS ASYNC
- 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.
- 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).
- 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.
- Always ensure err is null, if you are sending some data/results out.
- 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);
- If you are, too used to the functional pattern of coding, better avoid this.