Web API Cookbook Level Up Your Javascript Applications (Joe Attardi) (Z-Library)

Author: Joe Attardi

技术

JavaScript gives web developers great power to create rich interactive browser experiences, and much of that power is provided by the browser itself. Modern web APIs enable web-based applications to come to life like never before, supporting actions that once required browser plug-ins. Some are still in an experimental stage, but many are ready for use today. With this hands-on cookbook, author Joe Attardi helps you explore the powerful APIs available in modern browsers and guides you through the specific tasks that they unlock. Because these features are web standards, there is comprehensive documentation available from trusted resources such as MDN Web Docs. The knowledge you'll gain is transferable across different companies and projects. Learn the breadth of functionality available in modern browser APIs Explore future APIs that are still in an experimental stage Discover newer elements, such as dialog that replaces the need for a third-party library Build more powerful and interactive web applications using native APIs Understand the permissions model used by the browser to unlock functionality such as geolocation and push notifications

📄 File Format: PDF
💾 File Size: 3.3 MB
21
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
Joe Attardi Web API Cookbook Level Up Your JavaScript Applications
📄 Page 2
WEB DEVELOPMENT “Web API Cookbook covers a wide range of browser-based APIs and provides valuable examples for all skill levels. Plus, Joe’s writing style and thoughtful explanations make the learning enjoyable. This is a must-read for web developers!” —Sarah Shook Software developer/owner, Shook LLC “This book offered fresh insights and introduced me to APIs I never knew existed.” —Bret Little Staff Software Engineer, Shopify Web API Cookbook linkedin.com/company/oreilly-media youtube.com/oreillymedia JavaScript gives web developers great power to create rich interactive browser experiences, and in the modern web development age, much of that power is provided by the browser itself. Modern web APIs enable web-based applications to come to life like never before, supporting actions that once required browser plug-ins. Some of these APIs are still in the experimental stage, but many are ready for use today. With this hands-on cookbook, author Joe Attardi helps you explore the powerful APIs available in modern browsers and guides you through the specific tasks that they unlock. Because these features are web standards, there is comprehensive documentation available from trusted resources such as MDN Web Docs. The knowledge you’ll gain is transferable across different companies and projects. • Level up your web applications by giving them native-like features • Learn the breadth of functionality available in modern browser APIs • Explore future APIs that are still in experimental stages • Discover newer elements, such as dialogue that replaces the need for a third-party library • Build more powerful and interactive web applications by integrating with native device capabilities • Understand the permissions model used by browsers to unlock functionality such as geolocation and push notifications Joe Attardi has more than 20 years of frontend software development experience and has built many browser-based applications. He’s also built rich frontend experiences for Nortel, Dell, Constant Contact, Salesforce, and Synopsys, and he specializes in JavaScript and TypeScript development. US $59.99 CAN $74.99 ISBN: 978-1-098-15069-3
📄 Page 3
Joe Attardi Web API Cookbook Level Up Your JavaScript Applications Boston Farnham Sebastopol TokyoBeijing
📄 Page 4
978-1-098-15069-3 [LSI] Web API Cookbook by Joe Attardi Copyright © 2024 Joseph Attardi. 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://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Acquisitions Editor: Amanda Quinn Development Editor: Virginia Wilson Production Editor: Beth Kelly Copyeditor: Piper Editorial Consulting, LLC Proofreader: Tove Innis Indexer: WordCo Indexing Services, Inc. Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Kate Dullea April 2024: First Edition Revision History for the First Edition 2024-03-21: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781098150693 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Web API Cookbook, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. The views expressed in this work are those of the author and do not represent the publisher’s views. 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.
📄 Page 5
Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix 1. Asynchronous APIs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.0 Introduction 1 1.1 Working with Promises 2 1.2 Loading an Image with a Fallback 4 1.3 Chaining Promises 6 1.4 Using the async and await Keywords 7 1.5 Using Promises in Parallel 8 1.6 Animating an Element with requestAnimationFrame 9 1.7 Wrapping an Event API in a Promise 12 2. Simple Persistence with the Web Storage API. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2.0 Introduction 15 2.1 Checking for Web Storage Support 17 2.2 Persisting String Data 18 2.3 Persisting Simple Objects 18 2.4 Persisting Complex Objects 20 2.5 Listening for Storage Changes 24 2.6 Finding All Known Keys 25 2.7 Removing Data 27 3. URLs and Routing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 3.0 Introduction 29 3.1 Resolving a Relative URL 30 3.2 Removing Query Parameters From a URL 32 3.3 Adding Query Parameters to a URL 33 3.4 Reading Query Parameters 36 iii
📄 Page 6
3.5 Creating a Simple Client-Side Router 37 3.6 Matching URLs to Patterns 39 4. Network Requests. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 4.0 Introduction 43 4.1 Sending a Request with XMLHttpRequest 44 4.2 Sending a GET Request with the Fetch API 45 4.3 Sending a POST Request with the Fetch API 46 4.4 Uploading a File with the Fetch API 48 4.5 Sending a Beacon 48 4.6 Listening for Remote Events with Server-Sent Events 50 4.7 Exchanging Data in Real Time with WebSockets 51 5. IndexedDB. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 5.0 Introduction 55 5.1 Creating, Reading, and Deleting Objects in a Database 57 5.2 Upgrading an Existing Database 63 5.3 Querying with Indexes 64 5.4 Searching for String Values with Cursors 67 5.5 Paginating a Large Data Set 68 5.6 Using Promises with the IndexedDB API 70 6. Observing DOM Elements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 6.0 Introduction 73 6.1 Lazy Loading an Image When Scrolled into View 75 6.2 Wrapping IntersectionObserver with a Promise 76 6.3 Automatically Pause and Play a Video 77 6.4 Animating Changes in Height 78 6.5 Change an Element’s Content Based on Size 80 6.6 Applying a Transition When an Element Scrolls into View 82 6.7 Using Infinite Scrolling 83 7. Forms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 7.0 Introduction 85 7.1 Populating a Form Field from Local Storage 86 7.2 Submitting a Form with Fetch and the FormData API 88 7.3 Submitting a Form as JSON 89 7.4 Making a Form Field Required 91 7.5 Constraining a Number Input 92 7.6 Specifying a Validation Pattern 92 7.7 Validating Forms 93 iv | Table of Contents
📄 Page 7
7.8 Using Custom Validation Logic 97 7.9 Validating a Checkbox Group 98 7.10 Validating a Field Asynchronously 101 8. The Web Animations API. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 8.0 Introduction 105 8.1 Applying a “Ripple” Effect on Click 107 8.2 Starting and Stopping Animations 109 8.3 Animating DOM Insertion and Removal 110 8.4 Reversing Animations 112 8.5 Showing a Scroll Progress Indicator 115 8.6 Making an Element Bounce 116 8.7 Running Multiple Animations Simultaneously 118 8.8 Showing a Loading Animation 119 8.9 Respecting the User’s Animation Preference 121 9. The Web Speech API. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 9.0 Introduction 123 9.1 Adding Dictation to a Text Field 125 9.2 Creating a Promise Helper for Speech Recognition 127 9.3 Getting the Available Voices 129 9.4 Synthesizing Speech 130 9.5 Customizing Speech Synthesis Parameters 131 9.6 Automatically Pausing Speech 132 10. Working with Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 10.0 Introduction 133 10.1 Loading Text from a File 133 10.2 Loading an Image as a Data URL 136 10.3 Loading a Video as an Object URL 137 10.4 Loading an Image with Drag and Drop 139 10.5 Checking and Requesting Permissions 141 10.6 Exporting API Data to a File 142 10.7 Exporting API Data with a Download Link 144 10.8 Uploading a File with Drag and Drop 146 11. Internationalization. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 11.0 Introduction 147 11.1 Formatting a Date 148 11.2 Getting the Parts of a Formatted Date 148 11.3 Formatting a Relative Date 149 Table of Contents | v
📄 Page 8
11.4 Formatting Numbers 151 11.5 Rounding Decimal Places 152 11.6 Formatting a Price Range 152 11.7 Formatting Measurement Units 153 11.8 Applying Pluralization Rules 154 11.9 Counting Characters, Words, and Sentences 155 11.10 Formatting Lists 157 11.11 Sorting an Array of Names 158 12. Web Components. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 12.0 Introduction 161 12.1 Creating a Component to Show Today’s Date 164 12.2 Creating a Component to Format a Custom Date 165 12.3 Creating a Feedback Component 167 12.4 Creating a Profile Card Component 170 12.5 Creating a Lazy Loading Image Component 172 12.6 Creating a Disclosure Component 173 12.7 Creating a Styled Button Component 176 13. UI Elements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 13.0 Introduction 179 13.1 Creating an Alert Dialog 180 13.2 Creating a Confirmation Dialog 182 13.3 Creating a Confirmation Dialog Web Component 185 13.4 Using a Disclosure Element 187 13.5 Showing a Popover 189 13.6 Manually Controlling a Popover 190 13.7 Positioning a Popover Relative to an Element 191 13.8 Showing a Tooltip 193 13.9 Showing a Notification 195 14. Device Integration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 14.0 Introduction 197 14.1 Reading the Battery Status 197 14.2 Reading the Network Status 200 14.3 Getting the Device Location 201 14.4 Showing the Device Location on a Map 203 14.5 Copying and Pasting Text 204 14.6 Sharing Content with the Web Share API 206 14.7 Making the Device Vibrate 207 14.8 Getting the Device Orientation 208 vi | Table of Contents
📄 Page 9
15. Measuring Performance. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 15.0 Introduction 211 15.1 Measuring Page Load Performance 212 15.2 Measuring Resource Performance 213 15.3 Finding the Slowest Resources 213 15.4 Finding Timings for a Specific Resource 214 15.5 Profiling Rendering Performance 215 15.6 Profiling Multistep Tasks 216 15.7 Listening for Performance Entries 218 16. Working with the Console. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 16.0 Introduction 221 16.1 Styling Console Output 221 16.2 Using Log Levels 222 16.3 Creating Named Loggers 223 16.4 Displaying an Array of Objects in a Table 224 16.5 Using Console Timers 226 16.6 Using Console Groups 227 16.7 Using Counters 229 16.8 Logging a Variable and Its Value 230 16.9 Logging a Stack Trace 230 16.10 Validating Expected Values 231 16.11 Examining an Object’s Properties 232 17. CSS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 17.0 Introduction 235 17.1 Highlighting Text Ranges 235 17.2 Preventing a Flash of Unstyled Text 238 17.3 Animating DOM Transitions 240 17.4 Modifying Stylesheets at Runtime 242 17.5 Conditionally Setting a CSS Class 242 17.6 Matching Media Queries 243 17.7 Getting an Element’s Computed Style 244 18. Media. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247 18.0 Introduction 247 18.1 Recording the Screen 247 18.2 Capturing an Image from the User’s Camera 250 18.3 Capturing a Video from the User’s Camera 252 18.4 Determining the System Media Capabilities 254 18.5 Applying Video Filters 255 Table of Contents | vii
📄 Page 10
19. Closing Thoughts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 19.0 Introduction 257 19.1 In Defense of Third-Party Libraries 257 19.2 Detect Features, Not Browser Versions 257 19.3 Polyfills 258 19.4 Looking Ahead to the Future 258 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261 viii | Table of Contents
📄 Page 11
Preface JavaScript has come a long way since its introduction in late 1995. In the early days, the core APIs built into web browsers were limited. More advanced functionality typically required third-party JavaScript libraries, or in some cases even browser plug-ins. A web API is a series of global objects and functions exposed by the browser. Your JavaScript code can use these to interact with the Document Object Model (DOM), perform network communication, integrate with native device features, and much more. Polyfills Older browsers can take advantage of some of these APIs by using polyfills. A polyfill is a JavaScript library that implements missing functionality. Polyfills are typically used for web API features that aren’t implemented in older browsers. While beneficial, polyfills do have some drawbacks: • They are loaded as third-party libraries, which add to your bundle size. • They generally aren’t maintained by the browser teams, so there may be bugs or inconsistencies. • Some advanced functionality can’t be polyfilled in a performant way, or at all. The Power of Modern Browsers Modern web APIs have two big advantages for the web platform: No more plug-ins In the past, much of this functionality was only available to native applications or clunky browser plug-ins. (Remember ActiveX and Flash?) ix
📄 Page 12
Fewer third-party dependencies Modern browsers provide considerable functionality that used to require third- party JavaScript libraries. Popular libraries such as jQuery, Lodash, and Moment are usually not needed anymore. Drawbacks of Third-Party Libraries Third-party libraries can be helpful with older browsers or newer functionality, but they have some costs: More code to download Using libraries increases the amount of JavaScript the browser has to load. Whether it’s bundled with your app or loaded separately from a content delivery network (CDN), your browser still has to download it. This translates into poten‐ tially longer loading times and higher battery usage on mobile devices. Increased risk Open source libraries, even popular ones, can be abandoned. When bugs or secu‐ rity vulnerabilities are found, there’s no guarantee of an update. Browsers, in general, are supported by large companies (the major browsers are from Google, Mozilla, Apple, and Microsoft), and it’s more likely that these issues will be fixed. This isn’t to say that third-party libraries are bad. There are many benefits as well, especially if you need to support older browsers. Like everything in software develop‐ ment, library use is a balancing act. Who This Book Is For This book is intended for software developers with some experience with JavaScript who want to get the most out of the web platform. It assumes that you have a good knowledge of the JavaScript language itself: syntax, language features, and standard library functions. You should also have a working knowledge of the DOM APIs used for building interactive, browser-based JavaScript applications. There is a wide range of recipes in this book; there’s something for developers of all skill and experience levels. What’s in This Book Each chapter contains a set of recipes—code examples for accomplishing a specific task. Each recipe has three sections: x | Preface
📄 Page 13
Problem Describes the problem the recipe solves. Solution Contains code and explanation that implements the recipe solution. Discussion A deeper discussion of the topic. This section may contain additional code exam‐ ples and comparisons with other techniques. Code samples and live demos are on the companion website, https://WebAPIs.info. Additional Resources By its nature, the web is changing all the time. There are many great resources avail‐ able online to help clarify any questions that might come up. CanIUse.com At the time of writing, some APIs in this book are still in development or an “experi‐ mental” phase. Watch for compatibility notes in recipes that use these APIs. For most features, you can check the latest compatibility data at https://CanIUse.com. You can search by the name of a feature and see the latest information about which browser versions support the API and any limitations or caveats for particular browser versions. MDN Web Docs MDN Web Docs is the de facto API documentation for all things web. It covers all the APIs from this book in great detail, as well as other topics such as CSS and HTML. It contains in-depth articles and tutorials as well as API specifications. Specifications When in doubt, the specification of a feature or API is the definitive resource. They aren’t the most exciting reads, but they are a good place to look for details about edge cases or expected behavior. Different APIs have different standards, but most can be found either from the Web Hypertext Application Technology Working Group (WHATWG) or the World Wide Web Consortium (W3C). The standards for ECMAScript (which specifies features in the JavaScript Language) are maintained and developed by the Ecma International Technical Committee 39, better known as TC39. Preface | xi
📄 Page 14
Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program ele‐ ments such as variable or function names, databases, data types, environment variables, statements, and keywords. Constant width bold Shows commands or other text that should be typed literally by the user. Constant width italic Shows text that should be replaced with user-supplied values or by values deter‐ mined by context. This element signifies a tip or suggestion. This element signifies a general note. This element indicates a warning or caution. Using Code Examples Supplemental material (code examples, exercises, etc.) is available for download at https://github.com/joeattardi/web-api-cookbook. Also check out the companion web‐ site, where many of the code samples and recipes in this book are expanded into full, live, working examples. If you have a technical question or a problem using the code examples, please send email to bookquestions@oreilly.com. xii | Preface
📄 Page 15
This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission. We appreciate, but generally do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Web API Cookbook by Joseph Attardi (O’Reilly). Copyright 2024 Joe Attardi, 978-1-098-15069-3.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. O’Reilly Online Learning For more than 40 years, O’Reilly Media has provided technol‐ ogy and business training, knowledge, and insight to help companies succeed. Our unique network of experts and innovators share their knowledge and expertise through books, articles, and our online learning platform. O’Reilly’s online learning platform gives you on-demand access to live training courses, in-depth learning paths, interactive coding environments, and a vast collection of text and video from O’Reilly and 200+ other publishers. For more information, visit https://oreilly.com. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-889-8969 (in the United States or Canada) 707-827-7019 (international or local) 707-829-0104 (fax) support@oreilly.com https://www.oreilly.com/about/contact.html Preface | xiii
📄 Page 16
We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at https://oreil.ly/web-api-cookbook. For news and information about our books and courses, visit https://oreilly.com. Find us on LinkedIn: https://linkedin.com/company/oreilly-media Watch us on YouTube: https://youtube.com/oreillymedia Acknowledgments First of all, a heartfelt thanks to my family and friends for supporting me, especially to my wife, Liz, and son, Benjamin, for putting up with listening to my incessant typ‐ ing. When I am in the zone, I tend to type very quickly and loudly. Thank you to Amanda Quinn, Senior Content Acquisitions Editor, for bringing me on as an O’Reilly author. I’ve read countless O’Reilly books over the years and never thought I’d be writing one of my own one day. Thanks also to Louise Corrigan for making the introduction to Amanda and getting the process started (and who worked with me some years back publishing my very first book!). Special thanks to Virginia Wilson, Senior Development Editor, for guiding me throughout the process of writing the book and meeting regularly to keep things on track. I’d also like to thank the fantastic technical reviewers on this book: Martine Dowden, Schalk Neethling, Sarah Shook, and Adam Scott. The book turned out far better with their helpful feedback. Lastly, I’d like to give a shout out to the teams designing and developing these modern web APIs. Without them, this book would not exist! xiv | Preface
📄 Page 17
CHAPTER 1 Asynchronous APIs 1.0 Introduction A lot of the APIs covered in this book are asynchronous. When you call one of these functions or methods, you might not get the result back right away. Different APIs have different mechanisms to get the result back to you when it’s ready. Callback Functions The most basic asynchronous pattern is a callback function. This is a function that you pass to an asynchronous API. When the work is complete, it calls your callback with the result. Callbacks can be used on their own or as part of other asynchronous patterns. Events Many browser APIs are event based. An event is something that happens asynchro‐ nously. Some examples of events are: • A button was clicked. • The mouse was moved. • A network request was completed. • An error occurred. An event has a name, such as click or mouseover, and an object with data about the event that occurred. This might include information such as what element was clicked or an HTTP status code. When you listen for an event, you provide a callback function that receives the event object as an argument. 1
📄 Page 18
Objects that emit events implement the EventTarget interface, which provides the addEventListener and removeEventListener methods. To listen for an event on an element or other object, you can call addEventListener on it, passing the name of the event and a handler function. The callback is called every time the event is triggered until it is removed. A listener can be removed manually by calling removeEventListener, or in many cases listeners are automatically removed by the browser when objects are destroyed or removed from the DOM. Promises Many newer APIs use Promises. A Promise is an object, returned from a function, that is a placeholder for the eventual result of the asynchronous action. Instead of lis‐ tening for an event, you call then on a Promise object. You pass a callback function to then that is eventually called with the result as its argument. To handle errors, you pass another callback function to the Promise’s catch method. A Promise is fulfilled when the operation completes successfully, and it is rejected when there’s an error. The fulfilled value is passed as an argument to the then call‐ back, or the rejected value is passed as an argument to the catch callback. There are a few key differences between events and Promises: • Event handlers are fired multiple times, whereas a then callback is executed only once. You can think of a Promise as a one-time operation. • If you call then on a Promise, you’ll always get the result (if there is one). This is different from events where, if an event occurs before you add a listener, the event is lost. • Promises have a built-in error-handling mechanism. With events, you typically need to listen for an error event to handle error conditions. 1.1 Working with Promises Problem You want to call an API that uses Promises and retrieve the result. Solution Call then on the Promise object to handle the result in a callback function. To handle potential errors, add a call to catch. 2 | Chapter 1: Asynchronous APIs
📄 Page 19
Imagine you have a function getUsers that makes a network request to load a list of users. This function returns a Promise that eventually resolves to the user list (see Example 1-1). Example 1-1. Using a Promise-based API getUsers() .then( // This function is called when the user list has been loaded. userList => { console.log('User List:'); userList.forEach(user => { console.log(user.name); }); } ).catch(error => { console.error('Failed to load the user list:', error); }); Discussion The Promise returned from getUsers is an object with a then method. When the user list is loaded, the callback passed to then is executed with the user list as its argument. This Promise also has a catch method for handling errors. If an error occurs while loading the user list, the callback passed to catch is called with the error object. Only one of these callbacks is called, depending on the outcome. Always Handle Errors It’s important to always handle the error case of a Promise. If you don’t, and a Promise is rejected, the browser throws an exception for the unhandled rejection and could crash your app. To prevent an unhandled rejection from taking down your app, add a listener to the window object for the unhandledrejection event. If any Promise is rejected and you don’t handle it with a catch, this event fires. Here you can take action such as logging the error. 1.1 Working with Promises | 3
📄 Page 20
1.2 Loading an Image with a Fallback Problem You want to load an image to display on the page. If there’s an error loading the image, you want to use a known good image URL as a fallback. Solution Create an Image element programmatically, and listen for its load and error events. If the error event triggers, replace it with the fallback image. Once either the reques‐ ted image or the placeholder image loads, add it to the DOM when desired. For a cleaner API, you can wrap this in a Promise. The Promise either resolves with an Image to be added or rejects with an error if neither the image nor the fallback can be loaded (see Example 1-2). Example 1-2. Loading an image with a fallback /** * Loads an image. If there's an error loading the image, uses a fallback * image URL instead. * * @param url The image URL to load * @param fallbackUrl The fallback image to load if there's an error * @returns a Promise that resolves to an Image element to insert into the DOM */ function loadImage(url, fallbackUrl) { return new Promise((resolve, reject) => { const image = new Image(); // Attempt to load the image from the given URL image.src = url; // The image triggers the 'load' event when it is successfully loaded. image.addEventListener('load', () => { // The now-loaded image is used to resolve the Promise resolve(image); }); // If an image failed to load, it triggers the 'error' event. image.addEventListener('error', error => { // Reject the Promise in one of two scenarios: // (1) There is no fallback URL. // (2) The fallback URL is the one that failed. if (!fallbackUrl || image.src === fallbackUrl) { reject(error); } else { // If this is executed, it means the original image failed to load. 4 | Chapter 1: Asynchronous APIs
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List