CPIT-405 · WEB APPLICATIONS
Async & Ajax
Part 5: Talking to the server
Sync vs asyncPromisesAjaxXMLHttpRequestreadyStatefetchasync / await
01 · SYNCHRONOUS
One line at a time, in order
function syncFunction(a, b) { let sum = a + b; return sum;}console.log(syncFunction(5, 5));console.log("This is a synchronous function");
// console
10
This is a synchronous function
Calling a function: the program waits for it to return, then moves on
02 · ASYNCHRONOUS
It doesn't wait
function asyncFunction() { setTimeout(() => { console.log("This is an asynchronous function"); }, 2000);}asyncFunction();console.log("This is called immediately");
setTimeout
2 s
// console
This is called immediately
This is an asynchronous function
03 · WHY ASYNC?
The web is full of waiting
waiting for

A user event

Click
waiting for

A server response

waiting for

Data to load

✗ Waiting in line: the page freezes
✓ Async: the page stays responsive
04 · PROMISES
let promise = new Promise(function(resolve, reject) { setTimeout(function() { resolve('Promise resolved'); }, 500);}); promise .then(value => console.log(value)) .catch(reason => console.log(reason));
pendingstill waiting
fulfilledresolve(value) → then
rejectedreject(reason) → catch
05 · AJAX
Asynchronous JavaScript and XML
no reload
new data
1Ask the server in the background
2Update only one part of the page
XML→JSON today: lighter, JSON.parse built in
06 · AJAX IN JAVASCRIPT
Three ways to call an API
1 · oldest

XMLHttpRequest

events and readyState

2

fetch().then()

promises

3 · cleanest

async / await

fetch, written like sync code

PostmanGET https://api.github.com/users/octocat200 OK
07 · XMLHttpRequest
let xhr = new XMLHttpRequest();xhr.onreadystatechange = function() { if (xhr.readyState != 4) return; if (xhr.status === 200) { console.log(xhr.responseText); }};xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/', true);xhr.send();
1 · create2 · open(method, url)3 · send()4 · listen for the resultstatus 200 = OK
08 · xhr.readyState
Five states, from 0 to 4
0UNSENTcreated, open() not called
1OPENEDopen() called
2HEADERS_RECEIVEDheaders and status ready
3LOADINGdownloading, partial data
4DONEcomplete: use the data
09 · FETCH
fetch(url) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));
returnsPromise
then →
response.json()
then →
data{ … }
.catch(): network error
10 · ASYNC / AWAIT
async function getUser(name) { try { let response = await fetch("https://api.github.com/users/" + name); let data = await response.json(); console.log(data.login); } catch (error) { console.error(error); }}
✓ no .then() chain
✓ reads like synchronous code
errors: try / catch
11 · A REAL SEARCH
Search GitHub users
Search
GET api.github.com/search/users?q=octocat
200 OK
octocatgithub.com/octocat
octocat-devgithub.com/octocat-dev
octocatsgithub.com/octocats
NEXT
Your turn
Open the practice platform and start the Part 5 tab
Order the outputreadyStatePredict the asyncfetch & async challenges
0:00 / 0:00
← All partsPractice Part 5 →
Space: play / pause · ← →: scenes · M: voice on / off · C: subtitles · F: fullscreenDeveloped by: Fatmah Bamashmoos