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 ? 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();
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?
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);
Continuation Passing Style
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); });
CALLBACK STYLE PROGRAMMING
callbackhell.com
Promises
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
PROMISE
Callbacks
doStuff("cool", (err, results) => { // the rest of your code });
Promises
let doStuff = str => new Promise((resolve, reject) => {…}) doStuff("cool").then(…).catch(…).finally(…);
STATES
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
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
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
CATCH VS THEN
p.then(f1).catch(f2) vs. p.then(f1, f2)
not equal!
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 })
EVENT LOOP
setTimeout(() => alert("timeout")); new Promise(resolve => resolve()) .then(() => alert("promise")); alert("code");
What does this print?
EXAMPLE
Create a promise-based alternative for setTimeout
// function const delay = (ms) => { // your code here } // example delay(3000).then(() => { // do stuff });
CodePen
Async & Await
KEYWORD: async
Makes a function return a Promise Allows to use await in a function const hello = async () => ’Hello’ hello().then(console.log)
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) }
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(…)
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
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
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