
8 Tricks When Using the Fetch() API
In this Hasty Treat, Scott and Wes talk about 8 tricks to try when using the Fetch() API. Show Notes Welcome 1) Stream The Result // Create a new TextDecoder instance const decoder = new TextDecoder(); // Make the fetch request...
Syntax - Tasty Web Development Treats · Wes Bos & Scott Tolinski - Full Stack JavaScript Web Developers
August 21, 202319m 38s
Audio is streamed directly from the publisher (traffic.megaphone.fm) as published in their RSS feed. Play Podcasts does not host this file. Rights-holders can request removal through the copyright & takedown page.
Show Notes
In this Hasty Treat, Scott and Wes talk about 8 tricks to try when using the Fetch() API.
Show Notes // Create a new TextDecoder instance const decoder = new TextDecoder(); // Make the fetch request fetch('https://api.example.com/streaming-data') .then(response => { // Check if the response is valid if (!response.ok) { throw new Error('Network response was not ok'); } // Stream the response data using a TextDecoder const reader = response.body.getReader(); // Function to read the streamed chunks function read() { return reader.read().then(({ done, value }) => { // Check if the streaming is complete if (done) { console.log('Streaming complete'); return; } // Decode and process the streamed data const decodedData = decoder.decode(value, { stream: true }); console.log(decodedData); // Continue reading the next chunk return read(); }); } // Start reading the chunks return read(); }) .catch(error => { // Handle errors console.log('Error:', error); });- 06:05 2) Download Progress
- Download progress example
- 09:40 3) Cancel Streams - Abort Controller
const data = await fetch().catch(err => console.log(err));
- 14:42 6) to awaited - return error and data at top level
- await-to-js - npm
- 16:58 7) Dev tools - Copy as fetch
- 17:54 8) You can programatically create a Request, Response and Headers objects