Animations

API

Arrays

Async

Basics

Challenges

Classes

Console

Dates

Debugging

DOM Elements

DOM Methods

DOM Navigation

DOM Properties

Event Listeners

Flow Control

Forms

Functions

Global Functions

JSON

Keywords

Libraries (3rd party)

Math

Modules

Objects

Snippets

String

Types

Widgets

Window Object

JavaScript - fetch()

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:

  • The Promise (object) returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
  • fetch() won't receive cross-site cookies; you can’t establish a cross site session using fetch. Set-Cookie headers from other sites are silently ignored.
  • fetch won’t send cookies, unless you set the credentials init option.

Things to remember:

  • fetch() returns a promise ("response") object
  • use a .then call to evaluate the promise object
  • use then() for async calls that need to be awaited
  • the response is raw so we will prob need to turn it into json as shown in the code sample
  • this is an async call. your response must await 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();
}