MEAN — async package vs callbacks vs promises

Rachna Singhal
4 min readMay 30, 2018

--

As we all know from the previous posts (refer starting with MEAN and MVC in MEAN) that Node is an asynchronous language. So all your operations like file read and write, database read and write etc are asynchronous. In case we want to perform them synchronously we can utilise callbacks or promises or async package. I will be explaining each with an example.

For example we have the following task

  • Step 1 : Connect to a database
  • Step 2 : get user data
  • Step 3 : filter by age

Now in the above task you can perform step 2 only once the step 1 is done, and likewise for step 3 you need step 2 to have executed correctly.

In any other language a simple

openDatabase()
getData()
filterData()

would work correctly, but not in the case of NodeJS. To achieve this, we can do this in 3 ways.

CALLBACKS

When a function simply accepts another function as an argument, this contained function is known as a callback function. The easiest example is timeout function

setTimeout(function(){
console.log(“hey”)
}, 10)

setTimeout takes a function and an integer as input. Callback functions can also accept arguments.

Now for our task we can call the next function as part of callback function from within the function for example.

callback hell

In the above example, we call the openDatabase() function, which in turn call backs the callback function, which takes the connection and calls the getData() function which again calls another callback function which calls filterData() function.

The callback function is not run unless called by its containing function, it is called back. Hence, the term callback function

This example looks simple to understand, but as the dependency and complexity increases, we come into a state called callback hell which is multiple callbacks hierarchy. That is when the code becomes incomprehensible.

PROMISES

Like the name suggest, it is a promise. Something like,

I promise to do this if true else I won’t do.

With promises, we can ensure the execution of code block is synchronous and only done if the condition is true.

Promises have 3 states

  • Pending : This is the state before the execution of the promise
  • Fulfilled : If the promise was true
  • Rejected : If the promise was false

With promises, rather than an asynchronous call accepting a callback, it instead returns a promise. The calling code can then wait until that promise is fulfilled before executing the next step.

The promise is returned with two keywords

  • resolve() : in case the execution of asynchronous code was successful
  • reject() : in case the execution of asynchronous code failed

This is received by the calling function by two keywords again

  • then() : to receive in case code execution was success
  • catch(): to catch exceptions in case the promise is rejected.

Now our sample task can be performed this way

Promise chains

This makes the code easier to read. Essentially promises also internally uses callbacks.

Promises are asynchronous. Promises in functions are placed in a micro-task queue and run when other synchronous operations complete.

ASYNC

Async is a package in Node. This comes in handy when you need to perform some operations in parallel and some in series. The basic principle behind async is also callbacks but this makes the code readable. The above example will work like

async.series

This removes the complexity of initiating a promises, and makes code readable in case of multiple callbacks preventing callback hell.

It also helps in case where you need to perform a combination of synchronous and asynchronous task. For example, to get data from 2 tables in a database.

In that case we would run openDatabase() and then run the say getUserData and getEventData functions in parallel like

async series and parallel

CONCLUSION

Understanding these concepts of callbacks, promises and async package could be confusing but we have seen they are essential to better use Node and handle event loop in it.

You can use any and all in your code as per the complexity and demand of the code. I would not suggest which one to use, I would let you explore and choose one that you understand best and fits your requirements.

--

--

Rachna Singhal

Programmer, Sports Enthusiast, Theatre Lover, Blogger, Traveller, bibliophile