Skip to content

Node asynchronous programming style

Jim Amsden edited this page Feb 21, 2018 · 1 revision

Instead of executing code in a simple, synchronous, linear fashion, Node recognizes that most IO operations take significantly longer than in-memory operations and does these calls asynchronously so that the application is not stuck waiting for IO. This programming style is a different thought process and makes debugging a bit harder because the code does not read as it is executed. But it is a more realistic representation of how thing actually happen in the real world.

An asynchronous call always returns immediately. When the operation is completed, a callback function that is provided as an argument is invoked to do the next step.

  • Things that have to be done in a sequence have to use nested callbacks, or use async series to force the ordering of otherwise asynchronous functions.
  • callback functions can be defined before, after on in the call that requires them
  • define them inline if they are reasonably simple, not more than three levels of nesting, and don’t need to be called again somewhere else.
  • Nested callbacks in a function that need to refer to this of the function representing an instance of a class will need a variable such as _self set to this in order to access a specific outer scope.
  • to know what arguments the callback needs to provide, you have to read the documentation or implementation code for the call
  • callback functions should typically have two arguments: err and results. err represents an error return that can be tested when the callback is called. results represents the asynchronous “return” of the original function called. Keeping callbacks consistent allows them to be reused on different functions and easier to know what the arguments are.

Clone this wiki locally