Book Image

Mastering Web Application Development with Express

By : Alexandru Vladutu
Book Image

Mastering Web Application Development with Express

By: Alexandru Vladutu

Overview of this book

Table of Contents (18 chapters)
Mastering Web Application Development with Express
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Tiny modules for better control flow


In the getMovie() function from the movie.js model file, there are two places where we are performing parallel tasks. In both scenarios, we are creating counters and decrementing them in a custom callback function (called done or cb) that is executed when each asynchronous task finishes (the counters reach 0), and in the end, the main callback function is run.

Another thing we have taken care of in the custom callback function is whether or not the main callback function has been invoked (because passing an error argument at least once to the custom callback function will trigger this).

To get a better picture of the custom callback code, check out the following snippet:

var doneCalled = false;
var tasksCount = 2;
var done = function(err) {
  if (doneCalled) { return; }

  if (err) {
    doneCalled = true;
    return callback(err);
  };

  tasksCount--;

  if (tasksCount === 0) {
    movieInfo.trailers = trailers;
    movieInfo.cast = cast;

    callback...