Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Node.js Design Patterns
Node.js Design Patterns

Node.js Design Patterns: Master a series of patterns and techniques to create modular, scalable, and efficient applications

Arrow left icon
Profile Icon Mario Casciaro
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8 (28 Ratings)
Paperback Dec 2014 454 pages 1st Edition
eBook
Mex$631.99 Mex$902.99
Paperback
Mex$1128.99
Subscription
Free Trial
Arrow left icon
Profile Icon Mario Casciaro
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8 (28 Ratings)
Paperback Dec 2014 454 pages 1st Edition
eBook
Mex$631.99 Mex$902.99
Paperback
Mex$1128.99
Subscription
Free Trial
eBook
Mex$631.99 Mex$902.99
Paperback
Mex$1128.99
Subscription
Free Trial

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Node.js Design Patterns

Chapter 2. Asynchronous Control Flow Patterns

Moving from a synchronous programming style to a platform such as Node.js, where continuation-passing style and asynchronous APIs are the norm, can be frustrating. Writing asynchronous code can be a different experience, especially when it comes to control flow. Simple problems such as iterating over a set of files, executing tasks in sequence, or waiting for a set of operations to complete, require the developer to take new approaches and techniques to avoid ending up writing inefficient and unreadable code. One common mistake is to fall into the trap of the callback hell problem and see the code growing horizontally rather than vertically, with a nesting that makes even simple routines hard to read and maintain.

In this chapter, we will see how it's actually possible to tame callbacks and write clean, manageable asynchronous code by using some discipline and with the aid of some patterns. We will see how control flow libraries, such as async...

The difficulties of asynchronous programming


Losing control of asynchronous code in JavaScript is undoubtedly easy. Closures and in-place definition of anonymous functions allow a smooth programming experience that doesn't require the developer to jump to other points in the code base. This is perfectly in line with the KISS principle; it's simple, it keeps the code flowing, and we get it working in less time. Unfortunately, sacrificing qualities such as modularity, reusability, and maintainability will sooner or later lead to the uncontrolled proliferation of callback nesting, the growth in the size of functions, and will lead to poor code organization. Most of the time, creating closures is not functionally needed, so it's more a matter of discipline than a problem related to asynchronous programming. Recognizing that our code is becoming unwieldy—or even better, knowing in advance that it might become unwieldy—and then acting accordingly with the most adequate solution is what differentiates...

Using plain JavaScript


Now that we have met our first example of callback hell, we know what we should definitely avoid; however, that's not the only concern when writing asynchronous code. In fact, there are several situations where controlling the flow of a set of asynchronous tasks requires the use of specific patterns and techniques, especially if we are using only plain JavaScript without the aid of any external library. For example, iterating over a collection by applying an asynchronous operation in sequence is not as easy as invoking forEach() over an array, but it actually requires a technique similar to a recursion.

In this section, we will learn not only about how to avoid the callback hell but also about how to implement some of the most common control flow patterns using only simple and plain JavaScript.

Callback discipline

When writing asynchronous code, the first rule to keep in mind is to not abuse closures when defining callbacks. It can be tempting to do so, because it does...

The async library


If we take a look for a moment at every control flow pattern we have analyzed so far, we can see that they could be used as a base to build reusable and more generic solutions. For example, we could wrap the unlimited parallel execution algorithm into a function which accepts a list of tasks, runs them in parallel, and invokes the given callback when all of them are complete. This way of wrapping control flow algorithms into reusable functions can lead to a more declarative and expressive way to define asynchronous control flows, and that's exactly what async (https://npmjs.org/package/async) does. The async library is a very popular solution, in Node.js and JavaScript in general, to deal with asynchronous code. It offers a set of functions that greatly simplify the execution of a set of tasks in different configurations and it also provides useful helpers for dealing with collections asynchronously. Even though there are several other libraries with a similar goal, async...

Promises


We already mentioned at the beginning of the chapter that CPS is not the only way to write asynchronous code. In fact, the JavaScript ecosystem provides alternatives to the traditional callback pattern. One of these in particular is receiving a lot of momentum, especially now that it is going to be part of the ECMAScript 6 specification (also known as ES6 or Harmony), the upcoming version of the JavaScript language. We are talking, of course, about promises, and in particular about those implementations that follow the Promises/A+ specification (https://promisesaplus.com).

Note

There are other promises implementations that are not compliant to the Promises/A+ specification, and among those, the most popular is the one provided by JQuery. Most of the topics discussed in this section do not apply to those noncompliant implementations.

What is a promise?

In very simple terms, promises are an abstraction that allow an asynchronous function to return an object called a promise, which represents...

Generators


The ES6 specification introduces another mechanism that, besides other things, can be used to simplify the asynchronous control flow of our Node.js applications. We are talking about generators, also known as semi-coroutines. They are a generalization of subroutines, where there can be different entry points. In a normal function, in fact, we can have only one entry point, which corresponds to the invocation of the function itself. A generator is similar to a function, but in addition, it can be suspended (using the yield statement) and then resumed at a later time. Generators are particularly useful when implementing iterators, and this should ring a bell, as we have already seen how iterators can be used to implement important asynchronous control flow patterns such as sequential and limited parallel execution.

Note

In Node.js, generators are available starting from Version 0.11, but at the moment of writing, this feature is still not enabled by default and it's necessary to...

Comparison


At this point of the chapter, we should have a better understanding of what options we have to tame the asynchronous nature of Node.js. Each one of the solutions presented has its own pros and cons. Let's summarize them in the following table:

Solutions

Pros

Cons

Plain JavaScript

  • Does not require any additional library or technology

  • Offers the best performances

  • Provides the best level of compatibility with third-party libraries

  • Allows the creation of ad hoc and more advanced algorithms

  • Might require extra code and relatively complex algorithms

Async

  • Simplifies the most common control flow patterns

  • Is still a callback-based solution

  • Good performances

  • Introduces an external dependency

  • Might still not be enough for advanced flows

Promises

  • Greatly simplify the most common control flow patterns

  • Robust error handling

  • Part of the ES6 specification

  • Guarantee deferred invocation of onFulfilled and onRejected

  • Might require an external dependency

  • Require to promisify callback-based...

Summary


At the beginning of this chapter, we said that Node.js programming can be tough because of its asynchronous nature, especially for people used to developing on other platforms. However, throughout this chapter we showed how asynchronous APIs can be bent to our will, starting with plain JavaScript, which provided us the foundation for the analysis of more sophisticated techniques. We then saw that the tools at our disposal are indeed variegated and provide good solutions to most of our problems, in addition to offering a programming style for every taste; for example, we may choose async to simplify the most common flows, or totally change paradigm by using promises with their fluent chaining and robust error management, or if we want to get fancy, we can always leverage generators and feel like we are programming with blocking APIs.

This chapter should not only have taught you how to choose between one or the other solutions but also how to use them together, even in the same project...

Left arrow icon Right arrow icon

Key benefits

  • Dive into the core patterns and components of Node.js in order to master your application's design
  • Learn tricks, techniques, and best practices to solve common design and coding challenges
  • Take a code-centric approach to using Node.js without friction

Description

Node.js is a massively popular software platform that lets you use JavaScript to easily create scalable server-side applications. It allows you to create efficient code, enabling a more sustainable way of writing software made of only one language across the full stack, along with extreme levels of reusability, pragmatism, simplicity, and collaboration. Node.js is revolutionizing the web and the way people and companies create their software. In this book, we will take you on a journey across various ideas and components, and the challenges you would commonly encounter while designing and developing software using the Node.js platform. You will also discover the "Node.js way" of dealing with design and coding decisions. The book kicks off by exploring the fundamental principles and components that define the platform. It then shows you how to master asynchronous programming and how to design elegant and reusable components using well-known patterns and techniques. The book rounds off by teaching you the various approaches to scale, distribute, and integrate your Node.js application.

Who is this book for?

If you're a JavaScript developer interested in a deeper understanding of how to create and design Node.js applications, this is the book for you.

What you will learn

  • Design and implement a series of server-side JavaScript patterns so you understand why and when to apply them in different use case scenarios
  • Understand the fundamental Node.js components and use them to their full potential
  • Untangle your modules by organizing and connecting them coherently
  • Reuse well-known solutions to circumvent common design and coding issues
  • Deal with asynchronous code with comfort and ease
  • Identify and prevent common problems, programming errors, and anti-patterns

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 30, 2014
Length: 454 pages
Edition : 1st
Language : English
ISBN-13 : 9781783287314
Vendor :
Node.js Developers
Languages :
Concepts :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Dec 30, 2014
Length: 454 pages
Edition : 1st
Language : English
ISBN-13 : 9781783287314
Vendor :
Node.js Developers
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Mex$85 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Mex$85 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Mex$ 3,262.97
Web Development with MongoDB and Node.js
Mex$1004.99
Node.js Design Patterns
Mex$1128.99
MEAN Web Development
Mex$1128.99
Total Mex$ 3,262.97 Stars icon
Banner background image

Table of Contents

8 Chapters
Node.js Design Fundamentals Chevron down icon Chevron up icon
Asynchronous Control Flow Patterns Chevron down icon Chevron up icon
Coding with Streams Chevron down icon Chevron up icon
Design Patterns Chevron down icon Chevron up icon
Wiring Modules Chevron down icon Chevron up icon
Recipes Chevron down icon Chevron up icon
Scalability and Architectural Patterns Chevron down icon Chevron up icon
Messaging and Integration Patterns Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8
(28 Ratings)
5 star 89.3%
4 star 7.1%
3 star 0%
2 star 3.6%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




David AB Nov 10, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Read this and you'll get serious and deep understanding of node.js, and specific ways to implement in your project.Great discussion and solutions to avoid the sync vs async design and implementation issues in node.This is the most advanced complete and useful node.js book I've read.I enjoy it very much, and keep coming back to it to help me design and code.Thank you Mario for all the times you didn't go out for beers with your friends so you could publish your bookKudos to Packt and the reviewers. Great job, Great Book!
Amazon Verified review Amazon
Jarno Virta Dec 25, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is an absolutely fabulous book on nodejs. It is very well written and the code examples are very good and useful. It is obvious that the author has very deep knowledge of the language and the design patterns he writes of.The book starts with an explanation of the fundamental principles of node and of how asynchronous tasks run in node. The book then covers different patterns for writing asynchronous code. Next, streams are explained. For me, these early chapters were extremely useful as asynchronous code and streams are quite new to me and often cause some problems. The other chapters cover design patterns in node, node modules, scaling node apps and messaging and integration patterns.What can I say, this is a must for anyone writing code in node. Everything in the book, including the code examples, are very useful in practice. Although the examples are not unnecessarily complex, I found that reading the book required quite a lot of attention. This may be in part due to the fact that I am new to node, but the book is definitely quite dense in many parts. I think that it is therefore a good idea to either bang out the example codes yourself or at least download them from the publisher's site and go through the code files with a lot of thought.
Amazon Verified review Amazon
P. Greenberg Mar 01, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I have been working with node.js for almost 2 years, and read several books on the subject, but this one is by far the best!The author takes a bottoms-up approach to teaching node.js, and does an outstanding job covering everything from beginner topics like the event loop and callback patterns to advanced topics like scaling. In fact, of every published work on node.js I’ve read, this is the first that covers scaling, an essential part of real-world applications.The code examples in this book are also uniquely easy to follow, as the author uses footnotes to explain the important or confusing concepts. In addition, the examples explain the use case and construction of useful functions before revealing the node_module that already implements it, giving the reader an incredible depth of knowledge shared amongst few in the node community.I will be purchasing multiple copies of this book for our office and recommend it to anyone looking to learn more about node.js, from beginners to experienced developers.
Amazon Verified review Amazon
Tomer Ben David Apr 22, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
this is an amazing book. must have for any 2015+ software engineer!
Amazon Verified review Amazon
L M Feb 20, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Assolutamente suggerito a tutti coloro che conoscono Javascript ma non sono del tutto convinti che Node.js possa essere un'ottima soluzione per lo sviluppo di applicazioni enterprise. Questo libro vi farà completamente cambiare idea e vi introdurrà ai principali design pattern utili per essere immediatamente operativi ed evitare errori grossolani.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.