window.fetch

Added in ES 2015.
The Fetch API provides a global window.fetch() method for making asynchronous requests to REST APIs.


This is just a polyfill over XMLHttpRequest


let url = 'https://api.github.com/users/officeaddins/repos';  

var options = {
  method: "GET",
  headers: {
'Accept': 'application/vnd.github.v3+json',
'User-Agent': '.NET Foundation Repository Reporter',
  }
}


using Async Await


async function getRepositories_async() { 
  try {
    let response = await window.fetch(url, options);
    if (response.status === 200) {
       let data = await response.json();
       console.log(data);
    }
    else
    {
       console.log('Problem: ' + response.status);
    }
  } catch (error) {
    console.log(error);
  }
}

getRepositories_async();

You will often see these 4 lines as a single line.
Condensing your code to one line makes it much harder to read and to make changes later.

.catch( error => console.log(error) ); 


using Chaining



function Function_GetStatus(response) { 
   if (response.status !== 200) {
      return Promise.resolve(response)
   }
   else
   {
      return Promise.reject(new Error(response.statusText) )
   }
}

function Function_GetJson(response) {
   return response.json();
}

async function getRepositories_promise() {
  window.fetch(url, options)
    .then( Function_GetStatus)
    .then( Function_GetJson)
    .then( data => {
       console.log(data):
    } );
    } )
    .catch( error => console.log(error) );
}

getRepositories_promise();




using Promises

The fetch() method returns a promise so you can use the "then()" and "catch()" methods to handle it.

async function getRepositories_promise() { 
  window.fetch(url, options)
    .then( response => {
       if (response.status !== 200) {
          console.log('Problem: ' + response.status);
          return;
       }
       response.json()
         .then( data => {
            console.log(data):
         } );
    } )
    .catch( error => {
       console.log(error);
    }
  );
}

getRepositories_promise();

The fetch specification differs from the JQuery.ajax()



© 2022 Better Solutions Limited. All Rights Reserved. © 2022 Better Solutions Limited TopPrevNext