Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Mastering JavaScript Promises
Mastering JavaScript Promises

Mastering JavaScript Promises:

eBook
$39.59 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
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
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Mastering JavaScript Promises

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.

However, the name was changed to JavaScript when the version 2.0 B3 rolled out later. Since 1995, JavaScript has seen many ups and downs. There are stories of it being adopted, rejected, and adopted again. Soon after its launch, JavaScript gained a very popular response throughout the industry. Every major company contributed to its growth and used it after slight adjustment for their needs.

The fall and rise of JavaScript

The Netscape browser witnessed the fall of JavaScript in the late 90s and early 2000. The face of web development was maturing, but very few were still interested in investing in JavaScript.

It was the advent of the Mozilla foundation that released the first open source browser, Firefox, in early 2002-2003 since the base was the successor of the former Netscape browser. They employed JavaScript again within their product. In 2004, Google introduced Asynchronous JavaScript and XML (AJAX). This led to the foundation of many techniques and made communication easy with a black and white frontend and server by minimizing the server calls.

Google's contributions to JavaScript

Google has made more contributions in evolving, developing, and utilizing of JavaScript than any other organization. It was Google that introduced the V8 engine in its flagship web browser, Chrome. V8 is the backbone engine of the browser, and due to the smart usage of JavaScript, the browser is faster, robust, and adaptable to web and Android devices.

In the year 2009, Node.js arrived based on the same V8 engine as in Chrome. This is the server side of JavaScript, but far more better and advanced than what Netscape had introduced in late 90s. The whole idea of Node.js is to develop nonblocking input/output (I/O) and with few lines of codes, the server can serve up to 20K clients at a given slot of time.

Soon after Node.js, an entire stack of development has been introduced by the name of MEAN stack, which is an acronym of MongoDB, Express.js, Angular.js, and Node.js; where MongoDB is document based, NoSQL is a JavaScript-based database, Express.js is for a presentation layer, Angular.js is for frontend development of an app, and Node.js as the server that runs the entire show.

Where Promises.js came in?

Those of you who are aware of how a server-side script executes in an I/O event know that reading or writing data to and from a drive is blocking in nature, that is, during its execution, no other operation can be performed by a server-side language, even by the client. Well, with Promises.js, this is no longer the case. Promises.js utilizes a nonblocking strategy to perform I/O operations, so a client using your web app is free to perform any other tasks they want to without having to wait for the data read/write operation to be completed.

What is a promise?

When an eventual value is returned from the completion of a single operation, it represents a promise. If we analyze promise as a pact from human, it will help us understand the concept of promises in computer programming especially from the JavaScript perspective. Every promise is a pact among two or more parties to deliver some value to the other. The value can either be tangible or intangible, but a promise must deliver something in return. Until the promise is fulfilled, it remains in an unfulfilled state. However, when the said commitment has been made, the promise is said to be fulfilled. If the promise is not delivered as anticipated, the promise is said to fail.

So, what is a promise? According to the official definition:

Promise is an object or a function with a then method whose behavior confirms to this specification and represents the eventual result of an asynchronous operation.

The source of this definition is slide number 21 at http://www.slideshare.net/wookieb/callbacks-promises-generators-asynchronous-javascript.

Why do we need promise in JS?

Promises.js is a JavaScript library that promises asynchronous I/O operations such as reading and writing on a file. Whenever there is a callback method that involves making all operations related to I/O, they are to be made asynchronous. This extra callback parameter confuses our idea of what is the input and what will be its return value. It never works with control flow primitives. It also doesn't handle errors thrown by a callback method.

So, we need to handle errors thrown by a callback method, but also need to be careful not to handle errors thrown by the callback method. By the time we are done with this, our code will be a mess of error handling.

Despite all this mess of error handling code, we are still left with the problem of the extra callback parameter hanging around. Promises help you naturally handle errors, and write cleaner code by not having callback parameters.

Software prerequisites

Before starting Chapter 2, The JavaScript Asynchronous Model, you must need a set of prerequisite concepts that will make you better understand where to use Promises.js, and how it can save your time and effort in your recent or upcoming projects. The following section will elaborate what these concepts are and how we will use these as a base for our understanding of promise.

The prerequisite of this book is that you have a good understanding of procedural programing and a compulsory knowledge of basic JavaScript. Since this book is designed to develop a deeper knowledge of a concept (promise) and its use in different technologies, it's also imperative that you have a very good understanding of HTML and how to embed the code for your need.

An understanding of basic programming will help you begin with experiments with the help of a sample code as soon as you are done with any chapter/section. In this book, I've tried to make every section self-explanatory and every sample of code as a standalone script/program up to maximum strength. However, where there was need, we've added a snippet of code or algorithm to present our point more clearly.

Environment you need before getting started

To use the code within this book, you don't need any extra piece of software/IDE to start. To sample the code provided in this book, you only need free software/IDE such as Notepad++ or any other preferred open source GPL or GNU product.

Also, to view the result of your code, you need a web browser such as Google's Chrome or Mozilla's Firefox. For some examples related to Microsoft technologies, you will need Internet Explorer 9 or higher.

Future, promise, and delay

Future, promise, and delay describe an object that acts as proxy to a result that is initially unknown due to computation of its value, which is yet to be completed. They are normally referred to as constructs used for synchronizing in some concurrent programming language.

Daniel P. Friedman and David Wise proposed the term "promise" in 1975. Peter Hibbard called it "eventual". The term promise was coined by Liskov and Shrira, although they referred to the pipelining mechanism by the name "call-stream". The term promise refers to the fact that in completion of any said operation, an eventual value will be obtained. In the same way, the value can also be taken as eventual because it will only yield out on the occurrence of any event. Thus, both terms refer to the same fact simultaneously.

The terms future, promise, and delay are often used interchangeably. There is some core difference in implementing these terms. Future is revered as the read-only placeholder view of the variable, while promise is a writeable single assignment container that sets the value of the future.

In many cases, future promise are created together. In simple words, future is a value and promise is a function that sets the value. The future reruns the value of an async function (promise); setting the value of future is also called resolving, fulfilling, or binding it.

Promise pipelining

Using future can dramatically reduce the latency in distributed systems; for example, promise enables promise pipelining in programming languages E and Joule, which were also called call-stream in the Argus language.

A note to remember here is that promise pipelining should be distinguished from a parallel asynchronous message passing to a system supporting parallel message passing but not pipelining. It should also not be confused with pipelined message processing in actor systems, where it is possible for an actor to specify and begin executing a behavior for the next message before having completed processing of the current message.

Read-only views

The read-only view allows reading its value when resolved, but doesn't permit you to resolve it, thus making it possible to obtain a read-only view of the future.

The support for read-only views is consistent with the principle of least authority.

The read-only view enables you to set the value to be restricted to the subject that needs to set it. The sender of an asynchronous message (with result) receives the read-only promise for the result, and the target of the message receives the resolver.

States of a promise

Promise is based on three states. Each state has a significance and can be used to drive a certain level of result as per the need. This can help a programmer choose as per his/her need. The three states of a promise are as follows:

  • Pending: This is the initial state of a promise
  • Fulfilled: This is the state of a promise representing a successful operation
  • Rejected: This is the state of a promise representing a failed operation

Once a promise is fulfilled or rejected, it is immutable (that is, it can never change again).

With reference to the concepts discussed earlier, it's now clear what a promise is and how you can use it with all its potential.

How do we keep Promises.js in this book?

This book will cover the use of Promises.js with every major technology that has implemented the concept of promise. The book has been carefully divided into chapters to introduce, discuss, and explain the use of promise within that particular technology. Every chapter has its standalone set of examples of code to better understand the best use of Promises.js and its outcome.

The examples will be assuming that the selection of an operating system is purely your discretion. It may vary from reader to reader based on his/her licenses.

All the code is clearly printed with instructions and comments for a better understanding. Also, a soft copy is provided with this book enlisting every piece of code sorted in its respective chapter/section.

Browser compatibility

Promises support is extended to many modern browsers but not to all. A handy reference of what browser it supports is given in desktop and mobile screen resolutions:

  • Desktop compatibility:

    Feature

    Chrome

    Firefox

    Internet Explorer

    Opera

    Safari

    Basic support

    36

    31

    Not supported till IE 11. Added in

    Edge

    27

    8

  • Mobile compatibility:

    Feature

    Android

    Firefox Mobile (Gecko)

    IE Mobile

    Opera Mobile

    Safari Mobile

    Chrome for Android

    Basic support

    4.4.4

    31

    Edge

    Not supported

    Not supported

    42

Summary

In this chapter, we learned where JavaScript began and how it shaped into one of the leading technologies in modern application development. We discussed why there was a need for JavaScript in the early 90s and how this language has seen ups and downs throughout its existence.

We have also seen how investments from tech companies made their contributions in creating, developing, and evolving JavaScript as a major player in a dynamic and fast growing market of web, mobile, and real-time apps.

The adaptation of promises concept will make JavaScript much stronger and will help developers and engineers to write better code in an efficient manner.

In the next chapter, we will see what is an asynchronous model and how it's better fitted with JavaScript. This will help us understand to adopt and implement Promises.js in various languages.

Left arrow icon Right arrow icon

Description

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.

What you will learn

  • Get a complete overview of the promises paradigm and its advantages Discover the programming models that are used to build JavaScript Execute the asynchronous programming model in JavaScript and understand its usefulness in modern web development Employ promises in JavaScript to boost your project performance Apply the best practices of promises in JavaScript to your platform of choice Manage your JavaScript code in a more professional and maintainable manner Utilize promises effectively and efficiently in different domains and disciplines of software engineering Implement promises in WinRT, Node.js, jQuery, and Angular.js
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 24, 2015
Length: 188 pages
Edition : 1st
Language : English
ISBN-13 : 9781783985500
Languages :

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
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
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Jul 24, 2015
Length: 188 pages
Edition : 1st
Language : English
ISBN-13 : 9781783985500
Languages :

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 $ 109.98
JavaScript at Scale
$54.99
Mastering JavaScript Promises
$54.99
Total $ 109.98 Stars icon

Table of Contents

10 Chapters
1. Promises.js Chevron down icon Chevron up icon
2. The JavaScript Asynchronous Model Chevron down icon Chevron up icon
3. The Promise Paradigm Chevron down icon Chevron up icon
4. Implementing Promises Chevron down icon Chevron up icon
5. Promises in WinRT Chevron down icon Chevron up icon
6. Promises in Node.js Chevron down icon Chevron up icon
7. Promises in Angular.js Chevron down icon Chevron up icon
8. Promises in jQuery Chevron down icon Chevron up icon
9. JavaScript – The Future Is Now Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.5
(2 Ratings)
5 star 0%
4 star 0%
3 star 50%
2 star 50%
1 star 0%
Bin Liu Jan 16, 2017
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
I recommend another book "JavaScript with Promises: Managing Asynchronous Code", which is much better than this one.
Amazon Verified review Amazon
Amazon Customer Oct 05, 2015
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
I'm becoming increasingly disappointed with Packt books. Typos, inconsistent code formatting, code examples lack output printout. Moreover, the book ignores the wonderful promise library bluebird, and mentions that "the current node.js version is 0.10".I don't feel like this book has a significant value benefit over a few hours of using Google, StackOverflow, and bluebird documentation.
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 the digital copy I get with my Print order? Chevron down icon Chevron up icon

When you buy any Print edition of our Books, you can redeem (for free) the eBook edition of the Print Book you’ve purchased. This gives you instant access to your book when you make an order via PDF, EPUB or our online Reader experience.

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
Modal Close icon
Modal Close icon