From the course: Learning App Building with Vanilla JavaScript

Fetch API - JavaScript Tutorial

From the course: Learning App Building with Vanilla JavaScript

Start my 1-month free trial

Fetch API

- One common feature offered by modern libraries and frameworks is a convenience method for making AJAX requests. These methods let developers avoid needing to code the most widely supported vanilla JavaScript object, XMLHttpRequest or XHR. XHR code for multiple sequential AJAX requests, or callbacks, requires a set of nested functions which can result in a code structure that's difficult for humans to read and can create a call stack that presents debugging challenges. A newer paradigm builds on the promise's API, which is supported in modern browsers. Using a promise, you can execute code and then pass the result to a callback only when the code execution is complete. You can also chain callbacks. Each one passing its result to the next callback. Modern browsers support the Fetch API, which is a successor to XHR that's built on promises. You can create a Fetch request that specifies a URL and code one or more chained success callbacks as well as a callback to deal with a failed request. Fetch accepts additional arguments besides the URL, but by default it assumes basic settings, such as get for the http method. This reduces the amount of code necessary for most common requests. If you've used the AJAX convenience methods in modern libraries and frameworks, Fetch syntax will look very familiar. As many of these methods, such as those in jQuery or Angular, are also built on promises. The first plate I'm going to replace as I reset my table will be the jQuery AJAX code, which I'll swap out for Fetch code that will perform the same task but will work without a library.

Contents