Daniel Parker — «Javascript with Promises
Total Page:16
File Type:pdf, Size:1020Kb
JavaScript with Promises JAVASCRIPT Asynchronous JavaScript is everywhere, whether you’re using Ajax, “Daniel Parker begins with AngularJS, Node.js, or WebRTC. This practical guide shows intermediate an insightful introduction to advanced JavaScript developers how Promises can help you manage asynchronous code effectively—including the inevitable flood of callbacks to asynchronous WITH as your codebase grows. You’ll learn the inner workings of Promises and programming that any ways to avoid difficulties and missteps when using them. JavaScript developer will PROMISES The ability to asynchronously fetch data and load scripts in the browser find useful. JavaScript broadens the capabilities of JavaScript applications. But if you don’t with Promises covers understand how the async part works, you’ll wind up with unpredictable code that’s difficult to maintain. This book is ideal whether you’re new to both the How and Why, Promises or want to expand your knowledge of this technology. focusingn o current practical tools.” ■ Understand how async JavaScript works by delving into —Kris Kowal callbacks, the event loop, and threading Senior Software Engineer, Uber; creator of the Q library and CommonJS modules ■ Learn how Promises organize callbacks into discrete steps that are easier to read and maintain A comprehensive look ■ Examine scenarios you’ll encounter and techniques you can “ use when writing real-world applications at f one o the most important tools of a ■ Use features in the Bluebird library and jQuery to work with Promises modern JavaScript ■ Learn how the Promise API handles asynchronous errors programmer.” ■ Explore ECMAScript 6 language features that simplify —Domenic Denicola Software Engineer, Google; Editor, Promise-related code ES2015 Promises specification JavaScript with Daniel Parker is a software developer focused on web and mobile applications. He writes JavaScript for Evernote in Austin, Texas, and is the organizer of the Austin Google Developer Group. Promises Parker MANAGING ASYNCHRONOUS CODE PROGRAMMING/JAVASCRIPT Twitter: @oreillymedia facebook.com/oreilly US $19.99 CAN $22.99 ISBN: 978-1-449-37321-4 Daniel Parker JavaScript with Promises JAVASCRIPT Asynchronous JavaScript is everywhere, whether you’re using Ajax, “Daniel Parker begins with AngularJS, Node.js, or WebRTC. This practical guide shows intermediate an insightful introduction to advanced JavaScript developers how Promises can help you manage asynchronous code effectively—including the inevitable flood of callbacks to asynchronous WITH as your codebase grows. You’ll learn the inner workings of Promises and programming that any ways to avoid difficulties and missteps when using them. JavaScript developer will PROMISES The ability to asynchronously fetch data and load scripts in the browser find useful. JavaScript broadens the capabilities of JavaScript applications. But if you don’t with Promises covers understand how the async part works, you’ll wind up with unpredictable code that’s difficult to maintain. This book is ideal whether you’re new to both the How and Why, Promises or want to expand your knowledge of this technology. focusingn o current practical tools.” ■ Understand how async JavaScript works by delving into —Kris Kowal callbacks, the event loop, and threading Senior Software Engineer, Uber; creator of the Q library and CommonJS modules ■ Learn how Promises organize callbacks into discrete steps that are easier to read and maintain A comprehensive look ■ Examine scenarios you’ll encounter and techniques you can “ use when writing real-world applications at f one o the most important tools of a ■ Use features in the Bluebird library and jQuery to work with Promises modern JavaScript ■ Learn how the Promise API handles asynchronous errors programmer.” ■ Explore ECMAScript 6 language features that simplify —Domenic Denicola Software Engineer, Google; Editor, Promise-related code ES2015 Promises specification JavaScript with Daniel Parker is a software developer focused on web and mobile applications. He writes JavaScript for Evernote in Austin, Texas, and is the organizer of the Austin Google Developer Group. Promises Parker MANAGING ASYNCHRONOUS CODE PROGRAMMING/JAVASCRIPT Twitter: @oreillymedia facebook.com/oreilly US $19.99 CAN $22.99 ISBN: 978-1-449-37321-4 Daniel Parker JavaScript with Promises Daniel Parker Boston JavaScript with Promises by Daniel Parker Copyright © 2015 Daniel Parker. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://safaribooksonline.com). For more information, contact our corporate/ institutional sales department: 800-998-9938 or [email protected]. Editors: Simon St.Laurent and Brian MacDonald Indexer: Wendy Catalano Production Editor: Colleen Lobner Interior Designer: David Futato Copyeditor: Lindsy Gamble Cover Designer: Ellie Volckhausen Proofreader: Elise Morrison Illustrator: Rebecca Demarest June 2015: First Edition Revision History for the First Edition 2015-05-28: First Release 2015-07-17: Second Release See http://oreilly.com/catalog/errata.csp?isbn=9781449373214 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. JavaScript with Promises, the cover image of a white-crested helmetshrike, and related trade dress are trademarks of O’Reilly Media, Inc. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. 978-1-449-37321-4 [LSI] Table of Contents Preface. v 1. Asynchronous JavaScript. 1 Callbacks 2 Asynchronous JavaScript 3 Run to Completion and the Event Loop 6 Summary 10 2. Introducing Promises. 11 Basic Usage 11 Multiple Consumers 14 Promise States 15 Chaining Promises 18 Callback Execution Order 19 Basic Error Propagation 20 The Promise API 22 Summary 24 3. Working with Standard Promises. 25 The Async Ripple Effect 25 Conditional Logic 26 Parallel Execution 28 Sequential Execution Using Loops or Recursion 30 Managing Latency 35 Functional Composition 36 Summary 38 iii 4. Using Libraries and Frameworks. 39 Promise Interoperability and Thenables 40 The Bluebird Promise Library 40 Loading Bluebird 41 Managing Execution Context 42 Wrapping Node.js Functions 43 Working with Collections of Promises 46 Manipulating Fulfillment Values 48 Promises in jQuery 51 Summary 54 5. Error Handling. 55 Rejecting Promises 55 Passing Errors 57 Unhandled Rejections 58 Implementing try/catch/finally 59 Using the Call Stack 61 Summary 63 6. Combining ECMAScript 6 Features with Promises. 65 Destructuring 65 Arrow Functions 67 Iterables and Iterators 68 Generators 69 Synchronous Style 69 Generators and Iterators 70 Sending Values to a Generator 72 Sending Errors to a Generator 76 Practical Application 77 Summary 79 Index. 81 iv | Table of Contents Preface Asynchronous JavaScript is everywhere. AJAX, WebRTC, and Node.js are a few examples of where asynchronous APIs are found. Although it is easy to write a quick function to handle the result of one HTTP request, it is also easy to get lost in an unpredictable sea of callbacks as a codebase grows and more people contribute. That’s where a good approach for handling asynchronous code comes in and many develop‐ ers are choosing to use Promises in their approach. This is the book I needed when originally choosing an asynchronous strategy, and it is the result of my experience using promises in JavaScript applications. It explains their use and inner workings while exposing difficulties and missteps. Promises are made up of only a few concepts with a small API. But in the same way that JavaScript’s small number of simple constructs are used to create elegant and power‐ ful solutions, I am surprised and pleased at the number of ways Promises can be used to effectively manage asynchronous code. Intended Audience This book is for intermediate and advanced JavaScript developers who want to write asynchronous code. These developers may be comfortable with JavaScript for tradi‐ tional web APIs but are moving to environments such as Node.js, Google Chrome packaged apps, or building desktop applications with JavaScript. Developers who write browser-based code and want to use frameworks such as Angular or newer browser technologies such as Service Workers or WebRTC will also benefit. Even people who are already experienced with Promises may still enjoy reading the code and discovering additional ideas for their own work. A Word on Style This is not a book about JavaScript syntax dos and don’ts. All the examples are intended to be clear and casual; however, this style may conflict with some recom‐ v mended practices. Those choices are independent of the ideas presented here and you are free to choose as you see fit when approaching these concepts in your code. Conventions Used in This Book