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(); console.log(x + y);
Ca n ’ t retur n value s i n asyn c worl d ! function getY() { var y; $http.get(“/gety”, function(res){ y = res.y; }); return y; } var x = 5; var y = getY(); console.log(x + y);
Continuatio n Passin g Styl e
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
Promise s
PROMISE An object (unlike callback functions) which represent the eventual completion or failure of an async operation So fu ware 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 Callback s doStuff("cool", (err, results) => { // the rest of your code }); Promise s 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]) onFulfilled is the function to be called if the promise is fulfilled Has one argument: fulfillment value onRejected is the function to be called if the promise is rejected Has one argument: rejection reason Retur n valu e depend s o n handle r
SYNTAX p.catch(onRejected) Syntactic sugar for p.then(null, onRejected) onRejected is the function to be called if the promise is rejected Has one argument: rejection reason p.finally(onFinally) onFinally is the function called when the Promise is settled Bot h retur n Promise s
CHAINING abra(result => { abra() kadabra(result, newResult => { .then(result => kadabra(result)) alakazam(newResult, finalResult => { .then(newResult => alakazam(newResult)) console.log(`Magic: ${finalResult} .then(finalResult => { `) console.log(`Magic: ${finalResult} `) }, failureCallback) }) }, failureCallback) .catch(failureCallback); }, failureCallback) wit h Callback s wit h Promise s
CATCH VS THEN p.then(f1).catch(f2) vs . p.then(f1, f2) no t equa l !
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"); Wha t doe s thi s prin t ?
EXAMPLE Create a promise-based alternative for setTimeout // function const delay = (ms) => { // your code here } // example delay(3000).then(() => { // do stuff }); CodePen
Asyn c & Awai t
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 use try…catch instead of .catch(…) async function foo() { try { let response = await fetch('http://no-such-url'); } catch(err) { alert(err); // TypeError: failed to fetch } }
EXAMPLE 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)
RESOURCES Promise s MDN - Promise MDN - Using promises Javascript Promises: An Introduction | Google Developers The Modern Javascript Tutorial - Promise Asyn c / Awai t MDN - Making asynchronous programming easier with async and await The Modern Javascript Tutorial - Async/await
NEXT CLASS: NODE & EXPRESS https://uiuc-web-programming.gitlab.io/sp20/
Recommend
More recommend