Home » Node.js

Node.js - Optimal Performance Part -2

In this article, we will learn how to overcome challenges of asynchronous functions?
Submitted by Manu Jemini, on December 21, 2017

Prerequisite: Node.js - Optimal Performance Part -1.

Nothing comes for free. When we start to use asynchronous function a new scenario comes up. This is very essential to understand the loop holes it will create.

The Traditional error- handling is not made to catch the errors occurred during an asynchronous process. Which require a new type of error-handling.

Now let us learn this all new approach.

Express has built-in synchronous handling,

By default, Express will catch any exception thrown within the initial synchronous execution of a route and pass it along to the next error-handling middleware:

app.get('/', function (req, res) {
  throw new Error('oh no!')
});

Yet in asynchronous code, Express cannot catch exceptions as you’ve lost your stack once you have entered a callback:

For these cases, use the next function to propagate errors:

app.get('/', function (req, res, next) {

 a(function (err, data) {
    if (err) return next(err)
        
b(data, function (err, csv) {
      if (err) return next(err)
          })
})
app.use(function (err, req, res, next) {
  
	// handle error
})

In the above example, if any function a or b have any error it will handle it in the next function. Now the trick is next function.

Still, this isn’t bullet proof. There are two problems with this approach:

  1. You must explicitly handle every error argument.
  2. Implicit exceptions aren’t handled (like trying to access a property that isn’t available on the data object).

USE PROMISES

Now promises are very powerful and handy. First let us look on the code for the just the same thing as above.

app.get('/', function (req, res, next) {
  
  a()
    .then(function (data) {
      // handle data
      return b(data)
    })
    .then(function (csv) {
      // handle csv
    })
    .catch(next)
})
app.use(function (err, req, res, next) {
  // handle error
})

When the function a() finishes it will the first then() function and then second then(), if error occurred .catch() will be called.

This is very powerful read more about it if you are implementing Asynchronous functions.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.