Animations
API
Arrays
Async
Basics
Challenges
Classes
Console
Dates
Debugging
DOM Elements
DOM Methods
DOM Properties
Event Listeners
Flow Control
Forms
Functions
Global Functions
JSON
Keywords
Libraries (3rd party)
Math
Modules
Objects
Snippets
String
Types
Widgets
Window Object
Note: Look at await instead.
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.
This kind of functionality was previously achieved using XMLHttpRequest. Fetch provides a better alternative that can be easily used by other technologies such as Service Workers. Fetch also provides a single logical place to define other HTTP-related concepts such as CORS and extensions to HTTP.
The fetch specification differs from jQuery.ajax() in three main ways:
Things to remember:
fetch()
returns a promise
("response") object.then
call to evaluate the promise objectawait
the fetch call.https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
const url = 'https://api.github.com';
// fetch is async
const FetchData = () =>
{
// fetch is async and returns a promise obj
// we use the then() method to consume the promise object
fetch(url).then((promise) =>
{
// provide the callback function to the then() method
// this callback function receives the 'promise'... the data back from the api
// we need to parse the raw data as json
// the json method is also async so we need to use a then() as well.
promise.json().then((promiseJson) =>
{
console.log(promiseJson);
document.getElementById("demo").innerHTML =
`
${promiseJson.authorizations_url}<br />
${promiseJson.code_search_url}<br />
${promiseJson.emails_url}
`;
});
});
};
window.onload = function ()
{
FetchData();
}