Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
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

eBook
$22.99 $32.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
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 : 9781783287321
Vendor :
Node.js Developers
Languages :
Concepts :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want

Product Details

Publication date : Dec 30, 2014
Length: 454 pages
Edition : 1st
Language : English
ISBN-13 : 9781783287321
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 $5 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 $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 158.97
Web Development with MongoDB and Node.js
$48.99
Node.js Design Patterns
$54.99
MEAN Web Development
$54.99
Total $ 158.97 Stars icon

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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.