# Asychronous Coding --- ## Asychronous JQuery Recap ``` $.ajax({ url: 'https://dog.ceo/api/breeds/image/random', headers: { Accept: 'application/json' } }).then((response)=>{console.log(response)}); ``` --- ## Other Ajax Request ``` new XMLHTTPRequest() fetch() ``` --- ## XMLHTTPRequest (XHR) Built-in object for we browsers ``` const request = new XMLHttpRequest(); request.onreadystatechange = function () { console.log(this); }; request.open("GET", "https://dog.ceo/api/breeds/image/random"); request.send(); ``` --- ## fetch() ``` fetch('https://dog.ceo/api/breeds/image/random').then(response => {console.log(response)}); ``` --- ## fetch methods ``` GET POST PUT DELETE ``` --- ## POST with fetch() ``` const data = { username: 'example' }; fetch('https://exampleServeOrDBLocationURL/path', { method: 'POST', // or 'PUT' headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), }) ``` --- # Promises - Chaining - Error Handling - Statuses - Customized Promsies - Handling multiple promises at once --- ## Promises A promise is an *object* that represents a peice of data that will eventually arrive from an asychronus action. --- ## Promise Status ``` pending fullfilled rejected ``` --- ## How do they work {The object itself} ``` function logData(data){ console.log(data) } const data = fetch('url') data.then(logData) ``` --- ## How do we use a promise? We already have. Lets take a look ``` $.ajax({ url: 'https://dog.ceo/api/breeds/image/random' }).then(response => console.log(response)) fetch('https://dog.ceo/api/breeds/image/random').then(response => console.log(response)) ``` --- ## To resolve or not to resolve, that is the question? How can we customize our approach to promises? We do what we always do, Write functions and more functions. --- ## new Pomise () ``` const promise = new Promise((resolve, reject) => { resolve('Hello form Digital Crafts') }) ``` --- ## Returning custom promise *Why is this useful:* We want to be able to control where we get our data from. If we already have the data, we dont need to make un-necessary calls to an api to get it. Let's take a look --- ## Async Await ``` async function myFunction(){ try{ const data = await fetch('url') return data }catch(err){ console.log(err) return { err, message: "An error occurred in the server." } } return } ```