SEI-Example
  • Introduction
  • About These Notes
  • Syllabus
  • Development Workflow
    • Installfest
      • Mac OSX
      • Linux
      • Git Configuration
      • Sublime Packages
    • Command Line
      • The Terminal
      • Filesystem Navigation
      • File Manipulation
      • Additional Topics
    • Intro to Git
      • Version Control
      • Local Git
      • Remote Git
      • Git Recipes
    • Group Collaboration
      • Git Workflows
      • Project Roles and Tools
    • VS Code Tips & Tricks
  • HTML/CSS
    • HTML
    • CSS Selectors
    • CSS Box Model and Positioning
      • Box Model
      • Display and Positioning
      • Flexbox
      • Grid
      • Flexbox & Grid Games
      • Floats and Clears
      • Additional Topics
    • Advanced CSS
      • Responsive Design
      • Pseudo-Classes/Elements
      • Vendor Prefixes
      • Custom Properties
      • Additional Topics
    • Bootstrap
    • CSS Frameworks
    • Accessibility
  • JavaScript
    • Primitives
    • Arrays
    • Objects
    • Control Flow
      • Boolean Expressions
      • Conditionals
      • Loops
      • Promises
    • Functions
      • Callbacks
      • Timing Functions
      • Iterators
    • DOM and Events
    • DOM Manipulation
    • HTML5 Canvas
    • How To Reduce Redundancy
    • (2019) JavaScript OOP
    • (2016) OOP with Classes
    • (1995) OOP with Prototypes
      • Constructors
      • Prototypes
    • Intro to TDD
    • Scoping
    • Inheritance
      • Prototypal Inheritance
      • Call, Apply, and other Functions
      • ES6 Inheritance
      • Resources
    • Custom Node Modules
    • Additional Topics
      • AJAX, Fetch, and Async/Await
      • AJAX w/JSON and Localstorage
        • AJAX w/JSON
        • Local Storage
      • Async module
      • Data Scraping
  • jQuery
    • Intro
      • DOM Manipulation
      • Reddit Practice
      • Styling
      • Events
    • Plugins
    • AJAX
  • APIs
    • Fetch
    • AJAX w/jQuery
    • AJAX w/Fetch
  • Databases
    • Intro to SQL
    • Advanced SQL
    • MongoDB
      • Intro to NoSQL
      • CRUD in MongoDB
      • Data Modeling
      • Intermediate Mongo
  • Node/Express
    • Node
      • Intro to Node
      • Node Modules
      • Node Package Manager (NPM)
    • Express
      • Intro to Express
        • Routes
        • Views
        • Templates
        • Layouts and Controllers
        • CRUD & REST
          • Get and Post
          • Put and Delete
      • APIs with Express (request)
      • APIs with Express (axios)
    • Sequelize
      • Terminology
      • Setup
      • Using Models
      • Seeding Data
      • Validations and Migrations
      • Resources
      • 1:M Relationships
      • N:M Relationships
    • Express Authentication
      • Research Components
      • Code Components
      • Auth in Theory
        • Sessions
        • Passwords
        • Middleware
        • Hooks
      • Auth in Practice
        • Create the User
        • User Signup
        • Sessions
        • User Login
        • Authorization and Flash messages
    • Testing with Mocha and Chai
    • Mongoose
      • Mongoose Associations
    • JSON Web Tokens
      • Codealong
    • Additional Topics
      • oAuth
      • Geocoding with Mapbox
      • Geocoding and Google Maps
      • Cloudinary
      • Websockets with Socket.io
      • SASS
  • Ruby
    • Intro to Ruby
    • Ruby Exercises
    • Ruby Classes
    • Ruby Testing with Rspec
    • Ruby Inheritance
    • Ruby Data Scraping
  • Ruby on Rails
    • Intro to Rails
    • APIs with Rails
    • Asset Pipeline
    • Rails Auth and 1-M
      • Auth Components
    • Rails N:M
    • ActiveRecord Polymorphism
    • Additional Topics
      • oAuth
      • SASS
      • Rails Mailers
      • Cloudinary
      • Jekyll
  • React (Updated 2019)
    • ES6+/ESNext
      • Const and Let
      • Arrow Functions
      • Object Literals and String Interpolation
      • ES6 Recap
      • ES6 Activity
    • Intro to React
      • Create React App
      • Components and JSX
      • Virtual DOM
      • Props
      • Dino Blog Activity
      • Nested Components
      • Lab: LotR
    • React State
      • Code-Along: Mood Points
      • Code-Along: Edit Dino Blog
      • Lab: Simple Calc
      • Lifting State
    • React Router
      • Browser History/SPAs
      • React Router (lesson and full codealong)
      • Router Lab
    • Fetch and APIs
      • APIs with Fetch and Axios
      • Fetch the Weather
    • React Hooks
    • React LifeCycle
      • Lab: Component LifeCycle
    • React Deployment
    • Additional Topics
      • React Frameworks
        • Material UI Theming
      • Typescript
        • More Types and Syntax
        • Tsconfig and Declaration Files
        • Generics with Linked List
      • Redux
      • TypeScript
      • Context API
      • React Native
  • Meteor
  • Deployment and Config
    • Deploy - Github Pages
    • Deploy - Node/Sequelize
    • Deploy - Node/MongoDB
    • Deploy React
    • Deploy - Rails
      • Foreman (Environment Variables)
    • Deploy - AWS Elastic Beanstalk
    • Deploy - S3 Static Sites
    • Deploy - Django
    • Deploy - Flask
  • Data Structures and Algorithms
    • Recursion
    • Problem Solving - Array Flatten
    • Binary Search
    • Algorithm Complexity
    • Stacks and Queues
    • Bracket Matching
    • Ruby Linked Lists
      • Sample Code
      • Beginner Exercises
      • Advanced Exercises
    • JS Linked Lists
      • Sample Code
      • Beginner Exercises
      • Beginner Solutions
    • Hash Tables
    • Intro to Sorting
    • Insertion Sort
    • Bucket Sort
    • Bubble Sort
    • Merge Sort
    • Quick Sort
    • Heap Sort
    • Sorting Wrapup
    • Hashmaps
    • Trees and Other Topics
  • Python
    • Python Installation
    • Intro to Python
    • Python Lists
    • Python Loops
    • Python Dictionaries
    • Python Sets and Tuples
    • Python Cheatsheet
    • Python Functions
    • Python Classes
    • Python Class Inheritance
    • Intro to Flask
    • Intro to SQLAlchemy
      • Flask and SQLAlchemy
    • Using PyMongo
    • Intro to Django
    • CatCollector CodeAlong
      • URLs, Views, Templates
      • Models, Migrations
      • Model Form CRUD
      • One-to-Many Relations
      • Many-to-Many Relations
      • Django Auth
    • Django Cheatsheet
    • Django Auth
    • Django Polls App Tutorial
    • Django School Tool Tutorial
    • Django 1:M Relationships
    • Custom Admin Views
    • Data Structures and Algorithms
      • Recursion
      • Binary Search
      • Stacks and Queues
      • Linked Lists
      • Binary Trees
      • Bubble Sort
      • TensorFlow & Neural Networks
    • Adjacent Topics
      • Raspberry Pi
      • Scripting
  • Assorted Topics
    • History of Computer Science
    • Regular Expressions
    • Intro to WDI (Course Info)
    • Being Successful in WDI
    • Internet Fundamentals
      • Internet Lab
    • User Stories and Wireframing
      • Wireframing Exercise: Build an Idea
    • Post WDI
      • Learning Resources
      • Deliverables -> Portfolio
      • FAQ
  • Projects
    • Project 1
    • Project 2
    • Project 3
      • Project 3 Pitch Guidelines
    • Project 4
    • Past Projects
      • Project 1
      • Project 2
      • Project 3
      • Project 4
      • Portfolios
    • Post Project 2
    • MEAN Hackathon
      • Part 1: APIs
      • Part 2: Angular
    • Portfolio
  • Web Development Trends
  • Resources
    • APIs and Data
    • Tech Websites
    • PostgreSQL Cheat Sheet
    • Sequelize Cheat Sheet
    • Database Administration
  • Archived Section
    • (Archived) ReactJS
      • Intro to React
        • Todo List Codealong
        • Additional Topics
      • Deploy React
      • React with Gulp and Browserify
        • Setting up Gulp
        • Additional Gulp Tasks
      • React Router
        • OMDB Router
        • OMDB Search
        • Additional Resources
      • React Animations
        • CSS Animations
    • AngularJS
      • Intro to AngularJS
        • Components and SPA
        • Create an Angular App
      • Angular Directives and Filters
      • Angular Animation
      • Angular Bootstrap Directives
        • Bootstrap Modals
      • Angular $http
      • Angular Services
        • Service Recipes
        • ngResource
        • Star Wars Codealong
      • Angular Routing
      • Angular + Express
      • Angular Authentication
        • Additional Topics
      • Angular Components
      • Angular Custom Filters
      • Angular Custom Directives
Powered by GitBook
On this page
  • Learning Objectives
  • Roadmap
  1. JavaScript
  2. Additional Topics

AJAX, Fetch, and Async/Await

PreviousAdditional TopicsNextAJAX w/JSON and Localstorage

Last updated 3 years ago

Learning Objectives

Students Will Be Able To:

  • Describe the Use Case for AJAX

  • Use ES2017's async/await to handle promises synchronously

Roadmap

  1. Setup

  2. AJAX - What & Why

  3. Make an HTTP Request Using the Fetch API

  4. Use ES2017's async/await to Handle Promises

Setup

  • Create a new HTML, CSS, JS repl and name it something like AJAX with Fetch.

AJAX - What & Why

  • AJAX is short for Asynchronous JavaScript And XML.

  • Once upon a time, XML was the de facto format for transferring data between two computers - that's why it's in the name AJAX. However, JSON has since become the data transfer format of choice.

AJAX - What & Why

  • Clients (browsers) use AJAX to make HTTP requests using JavaScript.

  • Using AJAX, we can send an HTTP request that uses any HTTP method including, GET, POST, PUT & DELETE - no need for method-override!

AJAX - What & Why

  • But, here's the best part - unlike when we click a link or submit a form on a web page, AJAX does not trigger a page reload!

  • We can use AJAX to communicate with servers to do lots of things, including to read, create, update & delete data without the user seeing a page refresh.

  • AJAX has made possible the modern-day Single Page Application (SPA) like what you're going to build during this unit!

AJAX - What & Why

  • AJAX was originally made possible back in 1998 when IE5 introduced the XMLHttpRequest (XHR) object and today it's in all browsers. However, it's a bit clunky to use.

  • One of the reasons jQuery became popular was because it made making AJAX requests easier.

Make an HTTP Request Using the Fetch API

  • So, the A in AJAX stands for asynchronous.

  • Indeed, making an AJAX request is an asynchronous operation. So far, we've seen two approaches that enable us to run code after an asynchronous operation has completed. ❓ What are they?

Make an HTTP Request Using the Fetch API

  • The Fetch API, like any new Web API asynchronous method, uses promises instead of callbacks.

  •   fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => console.log(response))

Make an HTTP Request Using the Fetch API

  • To obtain the data in the body of the response, we need to call either the text or json method which returns yet another promise:

      // fetch defaults to making a GET request
      fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => response.json())
      .then(users => console.log(users))

    As you can see, the json() method returns a promise that resolves to the data returned by the server, as JSON.

Use ES2017's async/await to Handle Promises

  • The purpose of async/await is to allow us to work with asynchronous code almost as if it were synchronous!

Use ES2017's async/await to Handle Promises

  • We use the async declaration to mark a function as asynchronous when promises are going to be handled using await within it.

  • We can re-write our code to use async/await like this:

      async function printUsers() {
        const endpoint = 'https://jsonplaceholder.typicode.com/users';
        let users = await fetch(endpoint).then(res => res.json());
        console.log(users);
      }
    
      printUsers();

    The await operator causes the line of code with fetch to "pause" until the promise resolves with its value - in this case an array of users.

Use ES2017's async/await to Handle Promises

  • When using async/await, we cannot use a .catch() to handle a promise's rejection, instead we use JavaScripts's try/catch block:

      async function printUsers() {
        const endpoint = 'https://jsonplaceholder.typicode.com/users';
        let users;
        try {
          users = await fetch(endpoint).then(res => res.json());
          console.log(users);
        } catch(err) {
          console.log(err);
        } 
      }

    The catch block would run if the fetch failed.

Use ES2017's async/await to Handle Promises

  • So basically, we've seen that async/await replaces the .then(<function>) method for when a promise resolves.

  • In addition, JavaScript try/catch blocks replace the .catch(<function>) for error handling when a promise is rejected.

💪 Practice Exercise (2 MIN)

  • After the console.log(users), add another AJAX request using fetch to JSONPlaceholder's /posts endpoint.

  • Log out the returned posts.

References

We'll be using during this lesson to learn about AJAX and async/await.

In case you're wondering what the is about... It's the granddaddy of all markup languages, including HTML.

The browser can send AJAX requests to any API server, as long as the server is compliant.

However, we no longer have to use the XHR object or load jQuery to make AJAX calls thanks to the which is part of the collection of included in modern browsers.

Let's make a GET request to the /users endpoint of , a fake RESTful API for developers:

When ran, we'll see that the fetch method returns a promise that resolves to a Fetch object, which has properties such as status, etc.

Before we continue to use fetch any further, let's see how to use a fantastic new way of working with promises: &

Repl.it
XML
CORS
Fetch API
Web APIs
JSONPlaceholder
Response
async
await
MDN - Async Functions
MDN - Await Operator