Asynchronous Programming and Promises Async Await Prom Soft

  • Slides: 43
Download presentation
Asynchronous Programming and Promises. Async / Await Prom Soft. Uni Team Technical Trainers Software

Asynchronous Programming and Promises. Async / Await Prom Soft. Uni Team Technical Trainers Software University http: //softuni. bg ises Promises. then(). catch()

Table of Contents 1. Asynchronous Programming 2. Promises in JS – Concepts 3. Promises

Table of Contents 1. Asynchronous Programming 2. Promises in JS – Concepts 3. Promises with AJAX 4. Using Async / Await 2

Have a Question? sli. do #JSAPPS 3

Have a Question? sli. do #JSAPPS 3

Asynchronous Programming

Asynchronous Programming

Asynchronous Programming in JS § Asynchronous programming deals with the needs to run several

Asynchronous Programming in JS § Asynchronous programming deals with the needs to run several tasks (pieces of code) in parallel, in the same time § In JS the asynchronous programming is based on callbacks § You run a background task and pass a callback function 5

Asynchronous Programming – Example set. Timeout(task 1, 1000); 3 tasks run in parallel and

Asynchronous Programming – Example set. Timeout(task 1, 1000); 3 tasks run in parallel and set. Timeout(task 2, 1500); will finish at different time set. Timeout(task 3, 500); console. log("All tasks started"); function task 1() { console. log("task 1 finished") } function task 2() { console. log("task 2 finished") } function task 3() { console. log("task 3 finished") } All tasks started task 3 finished task 1 finished task 2 finished All tasks run in parallel task 1 task 2 task 3 6

Promises. then(). catch() Promises in JS Objects Holding Asynchronous Operations

Promises. then(). catch() Promises in JS Objects Holding Asynchronous Operations

What is a Promise? § A promise is an object holding an asynchronous operation

What is a Promise? § A promise is an object holding an asynchronous operation § A result which may be available now, or in the future, or never § Promises may be in one of these states: § Pending – operation still running (unfinished) § Fulfilled – operation finished (and the result is available) § Failed – operation is failed (and an error is available) § Promises in JS use the Promise object 8

JS Promises – Syntax let p = new Promise(function(resolve, reject) { // Do an

JS Promises – Syntax let p = new Promise(function(resolve, reject) { // Do an async task and then resolve or reject if (/* operation successful */) resolve('Success!'); else /* operation failed */ reject('Failure!'); }); p. then(function(result) { /* process the result (when the promise is resolved) */ }). catch(function(error) { /* handle the error (when the promise is rejected) */ }); 9

Promise. then() – Example console. log('Before promise'); new Promise(function(resolve, reject) { set. Timeout(function() {

Promise. then() – Example console. log('Before promise'); new Promise(function(resolve, reject) { set. Timeout(function() { resolve('done'); Before promise }, 500); After promise Resolved after 500 ms }) Then returned: done. then(function(result) { console. log('Then returned: ' + result); }); console. log('After promise'); Check your solution here: https: //judge. softuni. bg/Contests/360 10

Promise. catch() – Example console. log('Before promise'); new Promise(function(resolve, reject) { set. Timeout(function() {

Promise. catch() – Example console. log('Before promise'); new Promise(function(resolve, reject) { set. Timeout(function() { Before promise reject('fail'); After promise }, 500); fail Rejected after 500 ms }). then(function(result) { console. log(result); }). catch(function(error) { console. log(error); }); console. log('After promise'); Check your solution here: https: //judge. softuni. bg/Contests/360 11

Promise Execution let p = new Promise( function(resolve, reject) { if (/* operation successful

Promise Execution let p = new Promise( function(resolve, reject) { if (/* operation successful */) resolve('Success!'); else /* operation failed */ reject('Failure!'); }); p. then(function(result) { … }); . catch(function(reason) { … }); Promise executor resolve reject 12

JS Promises – Example – First Task let p 1 = new Promise( function(resolve,

JS Promises – Example – First Task let p 1 = new Promise( function(resolve, reject) { console. log("task 1 started. "); set. Timeout(function() { resolve("task 1 result"); console. log("task 1 finished. "); }, 1000); } ); 13

JS Promises – Example – Second Task let p 2 = new Promise( function(resolve,

JS Promises – Example – Second Task let p 2 = new Promise( function(resolve, reject) { console. log("task 2 started. "); set. Timeout(function() { resolve("task 2 result"); console. log("task 2 finished. "); }, 1500); } ); 14

JS Promises – Example – Third Task let p 3 = new Promise( function(resolve,

JS Promises – Example – Third Task let p 3 = new Promise( function(resolve, reject) { console. log("task 3 started. "); // reject('cannot execute task 3'); set. Timeout(function() { resolve("task 3 result"); console. log("task 3 finished. "); }, 500); } ); 15

JS Promises – Example – Execution console. log("All tasks started. "); Promise. all([p 1,

JS Promises – Example – Execution console. log("All tasks started. "); Promise. all([p 1, p 2, p 3]). then(function(result) { console. log("All tasks finished. "); console. log("Result: " + result. join(", ")); // non. Existing. Function(); Error in then() block }) will reject the promise. catch(function(error) { console. log("Some of the tasks failed. "); console. log("Error: " + error); }); Check your solution here: https: //judge. softuni. bg/Contests/360 16

Promises . then() . catch() Promises with j. Query AJAX

Promises . then() . catch() Promises with j. Query AJAX

Problem: Load Git. Hub Commits with AJAX Git. Hub username: <input type="text" id="username" value="nakov"

Problem: Load Git. Hub Commits with AJAX Git. Hub username: <input type="text" id="username" value="nakov" /> Repo: <input type="text" id="repo" value="nakov. io. cin" /> <button onclick="load. Commits()">Load Commits</button> <ul id="commits"></ul> <script> function load. Commits() { // AJAX call … } </script> 18

Solution: Load Git. Hub Commits with AJAX function load. Commits() { $("#commits"). empty(); let

Solution: Load Git. Hub Commits with AJAX function load. Commits() { $("#commits"). empty(); let url = "https: //api. github. com/repos/" + $("#username"). val() + "/" + $("#repo"). val() + "/commits"; $. get(url) j. Query AJAX methods. then(display. Commits) return promises. catch(display. Error); function display. Commits(commits) { … } } function display. Error(err) { … } 19

Solution: Load Git. Hub Commits with AJAX (2) function display. Commits(commits) { for (let

Solution: Load Git. Hub Commits with AJAX (2) function display. Commits(commits) { for (let commit of commits) $("#commits"). append($("<li>"). text( commit. author. name + ": " + commit. message )); } function display. Error(err) { $("#commits"). append($("<li>"). text("Error: " + err. status + ' (' + err. status. Text + ')')); } Check your solution here: https: //judge. softuni. bg/Contests/360 20

Problem: Blog (Posts with Comments) § Create a Kinvey app § Create user "peter"

Problem: Blog (Posts with Comments) § Create a Kinvey app § Create user "peter" with password "p" § Create posts "Post 1" and "Post 2" § Create comments "Com 1 a" and "Com 1 b" for "Post 1" § Create comments "Com 2 a", "Com 2 b" and "Com 2 c" for "Post 2" § Write a JS app to display all posts and view selected post along with its comments 21

Solution: Blog – Create a Kinvey App Remember your app ID 22

Solution: Blog – Create a Kinvey App Remember your app ID 22

Solution: Blog – Create User "peter" 23

Solution: Blog – Create User "peter" 23

Solution: Blog – Create the First Post Insert your Kinvey App ID here POST

Solution: Blog – Create the First Post Insert your Kinvey App ID here POST /appdata/kid_B 15 S 6 I 9 Zl/posts/ HTTP/1. 1 Host: baas. kinvey. com Authorization: Basic Z 3 Vlc 3 Q 6 Z 3 Vlc 3 Q= Content-Type: application/json Base 64(user: pass) { "title": "Post 1", "body": "Post #1 body" } { "title": "Post 1", "body": "Post #1 body", …, "_id": "582 cde 77209 db 9 d 9730 bab 03" } Remember the post _id 24

Solution: Blog – Create the Comments POST /appdata/kid_B 15 S 6 I 9 Zl/comments/

Solution: Blog – Create the Comments POST /appdata/kid_B 15 S 6 I 9 Zl/comments/ HTTP/1. 1 Host: baas. kinvey. com Use post _id from Authorization: Basic Z 3 Vlc 3 Q 6 Z 3 Vlc 3 Q= the previous request Content-Type: application/json { "text": "Com 1 a", "post_id": "582 cde 77209 db 9 d 9730 bab 03" } POST /appdata/kid_B 15 S 6 I 9 Zl/comments/ HTTP/1. 1 Host: baas. kinvey. com Authorization: Basic Z 3 Vlc 3 Q 6 Z 3 Vlc 3 Q= Content-Type: application/json { "text": "Com 2 a", "post_id": "582 cde 77209 db 9 d 9730 bab 03" } 25

Solution: Blog – Create the Second Post § Create the second post "Post 2"

Solution: Blog – Create the Second Post § Create the second post "Post 2" + its 3 comments § The "posts" and "comments" collections should look like these: 26

Solution: Blog – HTML Code <script src='data:image/svg+xml,%3Csvg%20xmlns=%22http://www.w3.org/2000/svg%22%20viewBox=%220%200%20415%20289%22%3E%3C/svg%3E' data-src="jquery-3. 1. 1. min. js"></script> <script src='data:image/svg+xml,%3Csvg%20xmlns=%22http://www.w3.org/2000/svg%22%20viewBox=%220%200%20415%20289%22%3E%3C/svg%3E' data-src="blog. js"></script>

Solution: Blog – HTML Code <script src="jquery-3. 1. 1. min. js"></script> <script src="blog. js"></script> <h 1>All <button <select <button Posts</h 1> id="btn. Load. Posts">Load</button> id="posts"></select> id="btn. View. Post">View</button> <h 1 id="post-title">Post Details</h 1> <ul id="post-body"></ul> <h 2>Comments</h 2> <ul id="post-comments"></ul> 27

Solution: Blog – JS Code $(document). ready(function() { const kinvey. App. Id = "kid_B

Solution: Blog – JS Code $(document). ready(function() { const kinvey. App. Id = "kid_B 15 S 6 I 9 Zl"; const service. Url = "https: //baas. kinvey. com/appdata/" + kinvey. App. Id; const kinvey. Username = "peter"; const kinvey. Password = "p"; const base 64 auth = btoa(kinvey. Username + ": " + kinvey. Password); const auth. Headers = { "Authorization": "Basic " + base 64 auth }; $("#btn. Load. Posts"). click(load. Posts. Click); $("#btn. View. Post"). click(view. Post. Click); function load. Posts. Click() { … } function view. Post. Click() { … }); 28

Solution: Blog – Load Posts function load. Posts. Click() { let load. Posts. Request

Solution: Blog – Load Posts function load. Posts. Click() { let load. Posts. Request = { url: service. Url + "/posts", headers: auth. Headers, }; $. ajax(load. Posts. Request). then(display. Posts). catch(display. Error); } 29

Solution: Blog – Display Posts as Options function display. Posts(posts) { $("#posts"). empty(); for

Solution: Blog – Display Posts as Options function display. Posts(posts) { $("#posts"). empty(); for (let post of posts) { let option = $("<option>"). text(post. title). val(post. _id); $("#posts"). append(option); } } 30

Solution: Blog – Handle AJAX Errors function display. Error(err) { let error. Div =

Solution: Blog – Handle AJAX Errors function display. Error(err) { let error. Div = $("<div>"). text("Error: " + err. status + ' (' + err. status. Text + ')'); $(document. body). prepend(error. Div); set. Timeout(function() { $(error. Div). fade. Out(function() { $(error. Div). remove(); }, 3000); } 31

Solution: Blog – Load Post Comments Query § Kinvey allows querying collections: https: //baas.

Solution: Blog – Load Post Comments Query § Kinvey allows querying collections: https: //baas. kinvey. com/appdata/kid_B 15 S 6 I 9 Zl/comments ? query={"post_id": "582 cde 77209 db 9 d 9730 bab 03"} 32

Solution: Blog – [View Post] Button Click function view. Post. Click() { let selected.

Solution: Blog – [View Post] Button Click function view. Post. Click() { let selected. Post. Id = $("#posts"). val(); if (!selected. Post. Id) return; let request. Posts = $. ajax({ url: service. Url + "/posts/" + selected. Post. Id, headers: auth. Headers }); let request. Comments = $. ajax({ url: service. Url + `/comments/? query={"post_id": "${selected. Post. Id}"}`, headers: auth. Headers }); Promise. all([request. Posts, request. Comments]). then(display. Post. With. Comments). catch(display. Error); } 33

Solution: Blog – Display Post with Its Comments function display. Post. With. Comments([post, comments])

Solution: Blog – Display Post with Its Comments function display. Post. With. Comments([post, comments]) { $("#post-title"). text(post. title); $("#post-body"). text(post. body); $("#post-comments"). empty(); for (let comment of comments) { let comment. Item = $("<li>"). text(comment. text); $("#post-comments"). append(comment. Item); } } Check your solution here: https: //judge. softuni. bg/Contests/360 34

Async / Await Simplified Promises

Async / Await Simplified Promises

Async / Await Simplify Promises async function load. Data() { return new Promise(function(resolve, reject)

Async / Await Simplify Promises async function load. Data() { return new Promise(function(resolve, reject) { set. Timeout(function() { resolve('data'); }, 300); } async function load. More. Data(input) { return new Promise(function(resolve, reject) { set. Timeout(function() { resolve(input + ' + more data'); }, 200); } 36

Async / Await Simplify Promises (2) async function load. All. Data() { console. log('Before

Async / Await Simplify Promises (2) async function load. All. Data() { console. log('Before promise'); let data = await load. Data(); let more. Data = await load. More. Data(data); console. log('Result: ' + more. Data); console. log('After promise'); } Before promise load. All. Data(); console. log('Finished'); Finished Result: data + more data After promise 37

Transpiling Async / Await with Babel npm install -g babel-cli npm install -g babel-plugin-transform-async-togenerator.

Transpiling Async / Await with Babel npm install -g babel-cli npm install -g babel-plugin-transform-async-togenerator. babelrc { "plugins": ["transform-async-to-generator"] } babel async-await. js -o async-await-transpiled. js 38

Promises. then(). catch() Practice: Promises, AJAX, Async / Await Live Exercises in Class (Lab)

Promises. then(). catch() Practice: Promises, AJAX, Async / Await Live Exercises in Class (Lab)

Summary § Promises hold operations (background tasks) § Can be resolved or rejected p.

Summary § Promises hold operations (background tasks) § Can be resolved or rejected p. then(function(result) { /* process the result */ }). catch(function(error) { /* handle the error */ }); § j. Query AJAX works with promises $. ajax(request). then(function(data) { … }). catch(function(error) { … }); 40

AJAX and j. Query AJAX ? s n stio e u Q ? ?

AJAX and j. Query AJAX ? s n stio e u Q ? ? ? https: //softuni. bg/courses/

License § This course (slides, examples, demos, videos, homework, etc. ) is licensed under

License § This course (slides, examples, demos, videos, homework, etc. ) is licensed under the "Creative Commons Attribution. Non. Commercial-Share. Alike 4. 0 International" license 42

Free Trainings @ Software University § Software University Foundation – softuni. org § Software

Free Trainings @ Software University § Software University Foundation – softuni. org § Software University – High-Quality Education, Profession and Job for Software Developers § softuni. bg § Software University @ Facebook § facebook. com/Software. University § Software University Forums § forum. softuni. bg