Mastering JavaScript Promises - Muzzamil Hussain - E-Book

Mastering JavaScript Promises E-Book

Muzzamil Hussain

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

This book is for all the software and web engineers wanting to apply the promises paradigm to their next project and get the best outcome from it. This book also acts as a reference for the engineers who are already using promises in their projects and want to improve their current knowledge to reach the next level. To get the most benefit from this book, you should know basic programming concepts, have a familiarity with JavaScript, and a good understanding of HTML.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 218

Veröffentlichungsjahr: 2015

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Mastering JavaScript Promises
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Promises.js
The fall and rise of JavaScript
Google's contributions to JavaScript
Where Promises.js came in?
What is a promise?
Why do we need promise in JS?
Software prerequisites
Environment you need before getting started
Future, promise, and delay
Promise pipelining
Read-only views
States of a promise
How do we keep Promises.js in this book?
Browser compatibility
Summary
2. The JavaScript Asynchronous Model
Programming models
The single-threaded synchronous model
The multithreaded synchronous model
The asynchronous programming model
Densities with an asynchronous programming model
Why do we need to block the task?
Why not use some more threads?
Learning the JavaScript asynchronous model
How JavaScript implements an asynchronous model
Callbacks in JavaScript
Blocking functions
The mechanism of a callback function in JavaScript
Basic rules to implement callbacks
Handling callback hell
The events
The mechanism of event handling
DOM – event capture and event bubbling
A list of the most common events handlers
Triggering functions in response to events
Types of events in JavaScript
Interface events
Mouse events
Form events
W3C events
Microsoft events
Mozilla events
The publisher/subscriber
A brief account of the observer pattern
A formal definition of observer
The push and pull model
The advent of observer/push-pub
The drawbacks of observer/push-pub
The promises object
Summing up – the asynchronous programing model
Summary
3. The Promise Paradigm
Callback, revisited
Promise
Deferred
How do promise and deferred relate to each other?
Standard behaviors of the Promise API
Interactive promises
The states and return values of a promise
Common sequencing patterns
Stacked
Parallel
Sequential
Decoupling events and applications logic
Promises as event emitters
What promises prescribed not to do
Avoiding getting into callback hell
Avoiding the use of unnamed promises
Promises and exceptions
The fail method
The then method
Best practices to handle exceptions in promise
Make your exceptions meaningful
Monitor, anticipate, and handle exception
Keep it clean
Considerations while choosing a promise
Summary
4. Implementing Promises
How to implement promises
Implementations in Java
The util package of Java
The mechanics of Java to implement a promise
The core components of java.util.concurrent
Executor
Queues
Timing
Synchronizers
Concurrent collections
The implementation of promise by Java
CompletionService
ExecutorService
Future
Delay and DelayedQueue
FutureTask
Summing up Java and Promises.js
Say hello to JDeferred
A few words about Android Deferred Object
Use case 1 – object success and failure callbacks for a task
Use case 2 – merging several promises
Mechanics of JDeferred
Features of JDeferred
Playing with the code using JDeferred
Deferred object and promise
Deferred Manager
Runnable and callable
wait() and waitSafely()
Filters
Pipes
Ultimate JDeferred
Summary
5. Promises in WinRT
An introduction to WinRT
The evolution of WinRT
A little detail about WinJS
WinJS – its purpose and a distribution history
WinJS on GitHub
HTML5, CSS3, and JavaScript
WT with HTML5, CSS3, and JavaScript
The need for integrating promise with WT
Problems when using asynchronous programming
Jumpstarting promises
Writing a function that returns a promise
Adding a change handler for input elements
Error handling
Chaining promises using the then() and done() functions
Example 1A – downloading a web page to a file using two asynchronous functions
Example 1B – downloading a web page to a file using startAsync
Summary
6. Promises in Node.js
The V8 engine – the mechanics
The V8 engine in Google Chrome
The evolution of Node.js
A brief introduction to Node.js
Download and install Node.js
Node Package Manager – NPM
Choice of environment
Setting up the environment for Node.js
A simple node server
Things we learned so far
Node.js with the Q library
Moving ahead with Q
Propagation in Q
Chaining and nesting promises
Sequences in Q
Combination in Q
How to handle errors in Q in Node.js
Making progress with promises
Getting to the end of a chain of promises
Callback-based promises versus Q-based promises
A few words on delay, timeout, and notify
Q.delay()
Q.timeout()
deferred.notify()
Q.Promise() – another way to create promises
Static methods of Q
Promise as a proxy
Familiarizing Node.js – the Q way
Unbinds and its solution
Q support for tracing stacks
Making promise-based actions
Object handling promises
Decomposition of primitive access
View revisited
Aborting a promise
Q utilities for Node.js
Summary
7. Promises in Angular.js
The evolution of Angular.js
The structure of the Angular.js document
Getting started with Angular.js
Creating your first Angular.js file
Step 1 – create the HTML 5 doc
Step 2 – add the JavaScript file to it
How to use Angular.js on your local machine
What would be your preference for the server?
Key elements of Angular.js
Supplying scope data
Filtering data
Controlling scopes
Routing views
Implementing promises in Angular.js
The schematics of using promises in Angular.js
Promise as a handle for callback
Blindly passing arguments and nested promises
Deferred objects or composed promises
Dealing with the nested calls
Concurrency in Angular.js
The combination of success and error
The safe approach
Route your promise
Summary
8. Promises in jQuery
From where it started?
Behind the scenes – how does jQuery work?
Is your document ready to submit?
How to use jQuery
The syntax
Caching in jQuery
A sample example
Selectors
Event methods
JavaScript before and after jQuery
The solution – introducing promises in jQuery
Deferred in jQuery
$.Deferred().promise() in jQuery
Projecting a promise in jQuery
Joining promises with $.when
Your own $.Deferred process
The advent of promises in jQuery
Summary
9. JavaScript – The Future Is Now
ECMAScript 6 (ECMA 262)
harmony:generators
The Fibonacci series
The MEAN stack
Real-time communication in JavaScript
Internet of Things
Computer animation and in 3D graphics
NoSQL databases
Summary
Index

Mastering JavaScript Promises

Mastering JavaScript Promises

Copyright © 2015 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: July 2015

Production reference: 1210715

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78398-550-0

www.packtpub.com

Credits

Author

Muzzamil Hussain

Reviewers

Luca Mezzalira

Jebin B V

Commissioning Editor

Edward Gordon

Acquisition Editor

Meeta Rajani

Content Development Editor

Ajinkya Paranjape

Technical Editor

Siddhi Rane

Copy Editor

Janbal Dharmaraj

Project Coordinator

Harshal Ved

Proofreader

Safis Editing

Indexer

Priya Sane

Graphics

Sheetal Aute

Production Coordinator

Komal Ramchandani

Cover Work

Komal Ramchandani

About the Author

Muzzamil Hussain has been working in the field of computing/information technology for more than a decade now. During this period, he developed a wide range of software products and services for companies around the world.

He completed his Digital Communications Networks course from the prestigious London Metropolitan University, London, United Kingdom. He is skilled in crafting software products and services with the best of technical and management skills, which he has acquired over the past 14 years.

The best part of his wealth of experience is the dual skill sets of project management and software engineering, which is a paramount feature of his work.

Muzzamil has worked with some of the big industries based in Pakistan, the UK, the USA, Canada, and UAE. These days, he is associated with Systems Limited, the first and one of the oldest software companies in Pakistan, in the capacity of senior project manager.

He also provides consultancy to start-ups on the software development life cycle, project management, release engineering, and continuous integrations.

He is also heavily involved in experimenting with the latest technologies such as the MEAN stack, an opinionated full-stack JavaScript framework, and Apache Hadoop for the distributed processing of large data sets.

He blogs at http://muzzamil.net/.

There are several people I would like to acknowledge and thank everyone who helped me not only in writing this book, but also those who were an inspiration to my professional growth, making me a better person.

Thanks to all those amazing people around me: my father, Mr. Musharraf Hussain, and my mother, Mrs. Rifat Hussain, who raised me with their best resources and provided a healthy foundation for my life. My teachers, who not only educated me with their best skills and knowledge, but also made me understand the tough lessons of life. Finally, my wife, Amber Muzzamil, and my daughters, Abeeha and Aroush, whose continuous and unconditional support was the biggest factor in making this book a reality.

About the Reviewers

Luca Mezzalira is a passionate Italian software developer with more than 10 years of experience in frontend technologies, in particular, JavaScript, HTML 5, Haxe, Flash, Flex, AIR, Lua, and Swift.

He has often been involved in cutting-edge projects for mobile (iOS, Android, and Blackberry), desktop, web, and embedded devices too for big corporations.

He really loves his job and tries to apply the Kaizen culture of continuous improvement and the XP principles and values in his daily life.

He strongly believes that agile and lean methodologies can help you achieve any goal during your job, improving yourself and the people you are working with.

In his spare time, Luca learns new technologies and methodologies by reading books and attending meetup events or conferences. He is very flexible and adaptive to any situation, always trying to achieve great goals in the best way possible.

He has collected different certifications and acknowledgements across the last 10 years, such as Certified Scrum Master and SAFe Agilist; Adobe Certified Expert and instructor on Flash, Flex, AIR, and Flash Lite; Adobe Community Professional; and Adobe Italy Consultant.

He has written for national and international technical magazines and is a technical reviewer for Packt Publishing.

He speaks at national and international conferences and community events, such as Lean Kanban United Kingdom, Flash Camp, Scotch on the Rocks, 360 Flex, PyCon, and so on.

In his spare time, Luca likes to watch football, play with his dogs, Paco and Maya, and study new programming languages.

The first mention is for my family that always helps me, in particular, my parents who support and inspire me everyday with their strength and love. A big thanks to my brother, who is also one of my best friends. He is the most intelligent person that I've ever met in my life; his suggestions and ideas are very important to me.

Then, I really have a lot of other friends to say thanks to for what we have created together until now. I hope to not forget anybody: Piergiorgio Niero, Chiara Agazzi, Alessandro Bianco, Raffaella Brandoli, Miguel Barreiro, Mark Stanley, Frank Amankwah, Matteo Oriani, Manuele Mimo, Goy Oracha, Tommaso Magro, Sofia Faggian, Matteo Lanzi, Peter Elst, Francesca Beordo, Federico Pitone, Tiziano Fruet, Giorgio Pedergnani, Andrea Sgaravato, Fabio Bernardi, Sumi Lim, and many others.

Last but not least, I'd like to say thanks to my girlfriend and my life partner, Maela, for the amazing time we spend together; her passion and commitment in our relationship gives me the strength to go ahead and do my best everyday. Really, thanks, my love!

Jebin B V is a young frontend developer by profession and a full-stack developer. He has been into web development for the past 4 years and has a very good command over the design and development of commercial web applications. He also has a very good sense of design, interaction, and UX when it comes to web development.

Jebin has developed applications for real-time messaging, big data management, visualization, network shopping management, CMS, social networking, and so on. He has great interest in JavaScript, so anything that is from the JavaScript background excites him. He also has experience in PHP and Java.

He possesses a very good notion of application-level design when it comes to building frontend applications. He has the nonstop habit of learning on an everyday basis. He spends a great deal of time on updating himself with new things coming up in frontend technologies. He loves to learn, teach, master, and lead in his field of expertise.

www.PacktPub.com

Support files, eBooks, discount offers, and more

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Free access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.

Preface

In this book, we will explore the concept and implementation of promises in JavaScript. This book has an evolving context that will lead you from a beginner's level to the master level of promises. Every chapter of this book will give you an outline to achieve a specific goal that will help you realize and quantify the amount of knowledge you absorb in every chapter.

The entire stack of chapters is designed in a way such that the book will evolve as you go through it. Every chapter in this book is designed in two parts: one is the concept building part and the other is the experimenting part, where you will be able to sample snippets of concepts, sometime in code, sometimes in best practices, and sometimes in images.

The first four chapters are more or less like theoretical knowledge to provide you with a solid foundation on JavaScript and promises. So, if you're a novice and don't know anything about JavaScript or promises, you will learn a great deal with these chapters. The rest of the chapters are more technology-oriented and you will learn implementation of promises in WinRT, Angular.js, jQuery, and Node.js. So, if you are a professional and already have some idea of promises, you may jump right into Chapter 5, Promises in WinRT, but I'd prefer it if you read through all the chapters for a better understanding of this book.

We will start with the introduction to JavaScript and how it has seen ups and downs from the late 90s up to the first decade of the twenty first century. We will focus on what asynchronous programing is and how JavaScript is using it. Moving on, I will introduce promises and its impact and how it's implemented. To make the book interesting and impart more knowledge to you, I will show you how promises has made its place in the heart of Java, one of the most mature object-oriented programming languages. This add-on content will act as a detour and clarify concepts in a more efficient way.

The flow of book will then lead you to the implementation of promises in some of the most used JavaScript libraries. We will see a sample code on how the mechanism of these libraries work. Finally, we will wrap up the book with our last chapter that will show you what is coming next in JavaScript, why it has gained so much attention over the past few years and what would be the possible future of JavaScript.

What this book covers

Chapter 1, Promises.js, covers the history of JavaScript and how it shaped into one of the leading technologies in modern application development. We will discuss why there was a need of JavaScript in the early 90s and how this language has seen ups and downs throughout its existence.

Chapter 2, The JavaScript Asynchronous Model, explains what a programming model is and how they are implemented in different languages, starting from a simple programming model to the synchronous model to the asynchronous model. We will also see how tasks are organized in memory and how they will serve according to their turns and priorities and how programming models decide what task is to be served.

Chapter 3, The Promise Paradigm, covers the paradigm of promise and the concept behind it. We will learn the conceptual knowledge of promise, deferred, common sequence of promise, and how promise helps in decoupling the business logic and application logic. We will also learn about the relationship between promises and event emitters and the concept behind the relation between promises and event emitters.

Chapter 4, Implementing Promises, discusses why we are implementing promises and why we chose Java as the core subject of this chapter. Java has richer features than any other programming language, and it also has better mechanism for asynchronous behavior. This chapter is the point where we start our journey to master promises.

Chapter 5, Promises in WinRT, explains how promises can be implemented in WinRT. We will see how promises evolved on the Windows platform and how it's contributing to different Windows-based devices.

Chapter 6, Promises in Node.js, covers what Node.js is, from where this most amazing library has evolved, who built it, and why and how it's helping us to create real-time web apps. We will see Q, the best way to offer promises to Node.js. We will see how we can work with Q, and then we will see different ways of using Q along with Node.js.

Chapter 7, Promises in Angular.js, explains how promises will be implemented in Angular.js, how it evolved and how promises will help in achieving applications composed for real-time web apps. We will also see the functionality of the Q library and the Angular.js implementation of promises using code and learn how to use them in our next application.

Chapter 8, Promises in jQuery, discusses how jQuery started taking shape and how it became a fundamental element of the modern-day web development. We will learn how to build basic jQuery documents and how to call the functions embedded into HTML files. We will learn why we started using deferred and promise in jQuery and how they are helping us to create cutting edge applications on both web-based platform and portable devices.

Chapter 9, JavaScript – The Future Is Now, covers how JavaScript is a game changer and how it has a bright future ahead. We will also explore why JavaScript has great tendency and adoptability, which will lead it to the next level of usage in almost every domain of computer science.

What you need for this book

If you are a software engineer who wants to learn more interesting facts about JavaScript to make your life easier, this book is for you. A simple and engaging language with narrations and code examples makes this book easy to understand and apply its practices. This book starts with an introduction to JavaScript promises and how it evolved over time. You will then learn the JavaScript asynchronous model and how JavaScript handles asynchronous programming. Next, you will learn about the promises paradigm and its advantages. Finally, this book will show you how to implement promises on platforms such as WinRT, jQuery, and Node.js, which are used in project development.

To get the best out of this book, you should know the basic programming concepts, the basic syntax of JavaScript, and possess a good understanding of HTML.

Who this book is for

This book is for all the software/web engineers who want to apply the promises paradigm in their next project and get the best outcome from it. This book has all the basic as well as advanced concepts of promises in JavaScript. This book can also act as a reference for the engineers who are already using promises in their projects and want to improve their current knowledge of this concept.

This book is a great resource for frontend engineers, but also serves as a learning guide for backend engineers who want to make sure their code collaborates seamlessly within the project.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "The click function will call (or execute) the callback function we passed to it."

A block of code is set as follows:

Q.fcall(imException) .then( // first handler-fulfill function() { }, );

Any command-line input or output is written as follows:

D:\> node –vD:\> NPM –v

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: " It should turn into green and display the Success message."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the ErrataSubmissionForm link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. Promises.js

In today's world, computer programming languages are getting much more advanced and there is a shift in the approach of using technologies. This is due to the fact that technology has been emerging with the rapid change in businesses and their needs. The vast expansion of business on electronic devices has led universities, researchers, and industries to invest in generating the latest technologies and tools that result in the inception of many new computer languages.

However, this is not the case with JavaScript. It's relatively new. It has been used and dumped at least three times by the modern programming landscape and is now widely accepted as the tool to develop modern, scalable, and real-time web applications in today's cyberspace.

In the mid 90s, the era of dot-com was born and it was during this time when companies wanted to dominate the newly created market called cyberspace. Although this was a virtual place and had no physical existence, the war for dominance was at its peak. Netscape Communications Corporation wanted its own variant of a lightweight interpreted language that would complement Java by appealing to nonprofessional programmers. This task was given to Brendan Eich who developed the first version of JavaScript with the name "Mocha". Officially, it was called LiveScript when it was first released in September 1995 in Netscape's browser in beta version 2.0.