ASYNC PROGRAMMING Wha t doe s thi s prin t ? function getY() { var - - PowerPoint PPT Presentation

async programming wha t doe s thi s prin t
SMART_READER_LITE
LIVE PREVIEW

ASYNC PROGRAMMING Wha t doe s thi s prin t ? function getY() { var - - PowerPoint PPT Presentation

CS 498RK SPRING 2020 ASYNC PROGRAMMING Wha t doe s thi s prin t ? function getY() { var y; $http.get(/gety, function(res){ // suppose the value of y on the server is 3 y = res.y; }); return y; } var x = 5; var y = getY();


slide-1
SLIDE 1

SPRING 2020 CS 498RK

ASYNC PROGRAMMING

slide-2
SLIDE 2

function getY() { var y; $http.get(“/gety”, function(res){ // suppose the value of y on the server is 3 y = res.y; }); return y; } var x = 5; var y = getY(); console.log(x + y);

What does this print?

slide-3
SLIDE 3

Can’t return values in async world!

function getY() { var y; $http.get(“/gety”, function(res){ y = res.y; }); return y; } var x = 5; var y = getY(); console.log(x + y);

slide-4
SLIDE 4

Continuation Passing Style

slide-5
SLIDE 5

CONTINUATION PASSING STYLE (CPS)

function getY(continueWith) { $http.get(“/gety”, function(res) { continueWith(res.y); }); } var x = 5; getY(function(y) { console.log(x + y); });

slide-6
SLIDE 6

CALLBACK STYLE PROGRAMMING

callbackhell.com

slide-7
SLIDE 7

Promises

slide-8
SLIDE 8

PROMISE

An object (unlike callback functions) which represent the eventual completion or failure of an async operation Sofuware abstraction to replace callbacks, to make working with async operations more pleasant (eg. avoiding "callback hell") Instead of passing callbacks into a function we attach callbacks to an object

slide-9
SLIDE 9

PROMISE

Callbacks

doStuff("cool", (err, results) => { // the rest of your code });

Promises

let doStuff = str => new Promise((resolve, reject) => {…}) doStuff("cool").then(…).catch(…).finally(…);

slide-10
SLIDE 10

STATES

slide-11
SLIDE 11

SYNTAX

let p = new Promise((resolve, reject) => {…}) "executor" does some async work and calls resolve / reject functions to settle the promise p.then(onFulfilled [, onRejected])

  • nFulfilled is the function to be called if the promise is fulfilled

Has one argument: fulfillment value

  • nRejected is the function to be called if the promise is rejected

Has one argument: rejection reason

Return value depends on handler

slide-12
SLIDE 12

SYNTAX

p.catch(onRejected) Syntactic sugar for p.then(null, onRejected)

  • nRejected is the function to be called if the promise is rejected

Has one argument: rejection reason p.finally(onFinally)

  • nFinally is the function called when the Promise is settled

Both return Promises

slide-13
SLIDE 13

CHAINING

abra(result => { kadabra(result, newResult => { alakazam(newResult, finalResult => { console.log(`Magic: ${finalResult} `) }, failureCallback) }, failureCallback) }, failureCallback)

abra() .then(result => kadabra(result)) .then(newResult => alakazam(newResult)) .then(finalResult => { console.log(`Magic: ${finalResult} `) }) .catch(failureCallback);

with Callbacks with Promises

slide-14
SLIDE 14

CATCH VS THEN

p.then(f1).catch(f2) vs. p.then(f1, f2)

not equal!

slide-15
SLIDE 15

COMPOSITION

Promise.all([p1, p2, p3]) .then(([result1, result2, result3]) => { // use result1, result2 and result3 }) Promise.race([p1, p2]) .then(result => { // result is from whichever p resolved faster })

slide-16
SLIDE 16

EVENT LOOP

setTimeout(() => alert("timeout")); new Promise(resolve => resolve()) .then(() => alert("promise")); alert("code");

What does this print?

slide-17
SLIDE 17

EXAMPLE

Create a promise-based alternative for setTimeout

// function const delay = (ms) => { // your code here } // example delay(3000).then(() => { // do stuff });

CodePen

slide-18
SLIDE 18

Async & Await

slide-19
SLIDE 19

KEYWORD: async

Makes a function return a Promise Allows to use await in a function const hello = async () => ’Hello’ hello().then(console.log)

slide-20
SLIDE 20

KEYWORD: await

Waits until the promise settles and returns its result

const logHello = async () => { const hello = await new Promise(resolve, reject) => { setTimeout(() => resolve('Hello'), 1000) }); console.log(hello) }

slide-21
SLIDE 21

HANDLING ERRORS

async function foo() { try { let response = await fetch('http://no-such-url'); } catch(err) { alert(err); // TypeError: failed to fetch } }

use try…catch instead of .catch(…)

slide-22
SLIDE 22

Rewrite the following code using async/await function loadData(url) { return fetch(url) .then(res => { if (res.status == 200) { return res.json(); } else { throw new Error(res.status); } }) } loadData('foo.json') .catch(alert);

EXAMPLE

slide-23
SLIDE 23

async function loadData(url) { let response = await fetch(url); if (response.status == 200) { let json = await response.json(); return json; } throw new Error(response.status); } loadData('foo.json') .catch(alert)

EXAMPLE

slide-24
SLIDE 24

RESOURCES

Promises

MDN - Promise MDN - Using promises Javascript Promises: An Introduction | Google Developers The Modern Javascript Tutorial - Promise

Async / Await

MDN - Making asynchronous programming easier with async and await The Modern Javascript Tutorial - Async/await

slide-25
SLIDE 25

NEXT CLASS: NODE & EXPRESS

https://uiuc-web-programming.gitlab.io/sp20/