CPIT-405 · WEB APPLICATIONS
Part 5: Talking to the server
Sync vs async Promises Ajax XMLHttpRequest readyState fetch async / 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" );
// 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 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));
pending still waiting
fulfilled resolve(value) → then
rejected reject(reason) → catch
05 · AJAX
A synchronous J avaScript a nd X ML
1 Ask the server in the background
2 Update 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
3 · cleanest async / await fetch, written like sync code
Postman GET 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 · create 2 · open(method, url) 3 · send() 4 · listen for the result status 200 = OK
08 · xhr.readyState
Five states, from 0 to 4
0 UNSENT created, open() not called
1 OPENED open() called
2 HEADERS_RECEIVED headers and status ready
3 LOADING downloading, partial data
4 DONE complete: use the data
09 · FETCH
fetch (url) .then (response => response.json ()) .then (data => console.log (data)) .catch (error => console.error (error));
returns Promise
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
GET api.github.com/search/users?q=octocat200 OK
octocat github.com/octocat
octocat-dev github.com/octocat-dev
octocats github.com/octocats
NEXT
Your turn
Open the practice platform and start the Part 5 tab
Order the output readyState Predict the async fetch & async challenges
⏮
▶
⏭
Voice
CC EN
✕