async programming wha t doe s thi s prin t
play

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();


  1. CS 498RK SPRING 2020 ASYNC PROGRAMMING

  2. 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);

  3. 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);

  4. Continuatio n Passin g Styl e

  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); });

  6. CALLBACK STYLE PROGRAMMING callbackhell.com

  7. Promise s

  8. 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

  9. 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(…);

  10. STATES

  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]) 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

  12. 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

  13. 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

  14. CATCH VS THEN p.then(f1).catch(f2) vs . p.then(f1, f2) no t equa l !

  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 })

  16. EVENT LOOP setTimeout(() => alert("timeout")); new Promise(resolve => resolve()) .then(() => alert("promise")); alert("code"); Wha t doe s thi s prin t ?

  17. EXAMPLE Create a promise-based alternative for setTimeout // function const delay = (ms) => { // your code here } // example delay(3000).then(() => { // do stuff }); CodePen

  18. Asyn c & Awai t

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

  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) }

  21. 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 } }

  22. 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);

  23. 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)

  24. 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

  25. NEXT CLASS: NODE & EXPRESS https://uiuc-web-programming.gitlab.io/sp20/

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend