I am going to write asynchronous code in multiple ways. You can execute asynchronous code in callback way or promises way.I am going to implement one use case by using following patterns

  1. Callback way (callback hell)
  2. Async Library
  3. Promises
  4. Async/await

USE CASE

I have three tables or collections in my database.

  1. Product
  2. Order
  3. ProductOrder

I am going to execute this flow and write asynchronous code in multiple ways.

CALLBACK WAY (CALLBACKHELL)

The problem with this approach is that it is difficult-to-read code. It is very hard to manage error handling . I personally recommend do not follow this approach

ASYNC LIBRARY

To avoid callback hell you can use async library method like async.series , async.waterfall . If you want to run your code in series you can use async.series method. I have used async.series in the below example

The async module guarantees only one callback will be fired. It also propagates errors and manages parallelism for us.You can use async.js methods. Read the documentation if you want to learn more about async.js

PROMISES

Promises is another great way to work with asynchronous code in Node.js .

As we can see from this example — promises is very much like streams, except they only emit a single value. You can think of the.then() method of promises as an equivalent of .pipe() for node streams.I would highly recommend to use promises rather than callbacks. There is great library bluebird.js to work with promises.

ASYNC/AWAIT

Node version 7 has included async/await. This is the one of the best approach to work with asynchronous code. I fell in love with this approach.

The async function declaration defines an asynchronous function, which returns an AsyncFunction object.

When an async function is called, it returns a Promise. When the async function returns a value, the Promise will be resolved with the returned value. When the async function throws an exception or some value, the Promise will be rejected with the thrown value.

An async function can contain an await expression, that pauses the execution of the async function and waits for the passedPromise’s resolution, and then resumes the async function’s execution and returns the resolved value.

BONUS EXAMPLE WITH ASYNC/AWAIT

You can also execute parallel tasks with async/await. Here is an example of parallel tasks

I have used all these approaches to handle asynchronous code in Node.js. Recently, I worked with async/await. I think this is the best way to work with async code in Node.js

 

If you want to learn more about Sails.js . Here is my new Sails.js course on Udemy .

Discount: 90 % off

Price: $10

couponCode=JUN_FS

Node:js : Building Rest Apis with Sails.js – Udemy