A Sync Programming

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 26

Asynchronous Programming

javascript-‫תכנות אסינכרוני ב‬

Internet Course
Dr Solange Karsenty
Hadasssah Academic College
‫תוכן‬
‫• מהו‪?asynchronous programming-‬‬
‫• מהו ‪?threads‬‬
‫• איך שומרים על דף אינטראקטיבי?‬
‫• כתיבת קוד אסינכרוני‬
‫למה ‪?Asynchronous‬‬
‫• לשמור על אינטרקציה עם המשתמש (הכוונה הדף לא קופא – קלט‪/‬פלט)‪ ,‬כאשר בו‬
‫זמנית יש חישובים‪:‬‬
‫• עיבוד נתונים‬
‫• תקשרת עם שרת (לדוגמא טעינת בזמן אמת של תחזית מזג אוויר)‬
‫• טיימר שרץ ברקע (לדוגמא אנימציה)‬

‫• ברגע שהאפליקציה עושה יותר מדבר אחד בו זמנית מדובר על ‪asynchronous‬‬


‫‪ - Threads‬תהליכונים‬
‫• סידרה של פקודות‬
‫• כאשר תהליכונים רצים בו זמנית אנחנו יוצרים‬
‫קוד אסינכרוני ‪asynchronous -‬‬
‫• ‪JavaScript‬‬
‫כל מה שכותבים רץ בתהליכון אחד(‪)event loop‬‬ ‫•‬
‫אין זיכרון משותף בין תהליכונים ולכן אין בעיות של‬ ‫•‬
‫תחרות‬
‫יש הרבה תהליכונים בתוך ה‪ runtime-‬של‬ ‫•‬
‫‪javascript‬‬
‫הלולאה הראשית מטפלת באירועים וקוראת‬ ‫•‬
‫לפונקציות – ‪callbacks/handlers‬‬
Timers

‫• טכניקה פשוטה על מנת ליצור קוד אסינכרומי‬


setTimeout (<function>, <after-ms>) •
example online •
function showSessionExpire(){
console.log("Your session expired");
}

setTimeout(showSessionExpire, 1000);
console.log("showSessionExpire will execute after 1000 ms");
‫הלולאה הראשית‬
• JS Engine manages an event loop.
• Example events: onclick, Ajax received
• For each event it checks if there is any listener registered for that
event
• If so it calls the listener callback/function
• Repeat

• The event loop is responsible for dispatching events when they occur
‫‪ - Event dispatching‬שליחת אירועים‬
‫• לכל רכיב יכול להיות מספר רב של מאזינים עבור מספר רב של אירועים‪ .‬אין שליטה‬
‫על סדר הקריאה!‬
‫• דוגמא של רכיבים ‪nested‬‬
Nested elements
• Listener 3, 2 and 1 get called
(it’s called bubbling, parents get
notified)
• Enable event capturing when you register your listener: Bubbling: the event is
• element.addEventListener(‘click’, myListener, true); first captured and handled
by the innermost element
and then propagated to
outer elements. (most
a boolean value specifying common)
• An individual listener can whether to use event
bubbling or event
stop bubbling/capturing by capturing
Capturing: the event is
calling: first captured by the
outermost element and
event.stopPropagation(); propagated to the inner
• Assuming that event is the name of your handler’s parameter
elements.
‫‪Writing “good” event handlers‬‬
‫• המנוע ‪JS‬לא מטפל באירוע הבא כל עוד הקוד (‪ )handler‬שלכם לא הסתיים!‬
‫• זה טוב כי אין לנו בעיות של תחרות‬
‫• זה רע כי אנחנו תוקעים את כל האפליקציה‬
‫• ‪Any alert box will block‬‬
‫• ‪Non asynchronous requests will block‬‬
‫• ‪If you must perform some long processing, separate it in multiple events‬‬
‫• תזכרו שהאירועים מגיעים בסדר לא ידוע מראש‬
‫• ‪ Handler‬חייב לבדוק את מצב האפליקציה על מנת לדעת אם הטיפול עדיין רלוונטי‬
‫• דוגמא?‬

‫• רוב הפונקציות ‪ async‬מאפשרות לכם לרשום טיפול עבור ‪errors‬‬


‫• רצוי להשתמש בזה!‬
Multithreaded programming?
‫• בסימסטר ב׳‬
‫‪ - Promises‬אבטחות‬
‫היה קיים בעבר כספריה‪ ,‬היום בנוי בתוך הדפדפן‬ ‫•‬
‫‪ Promise‬זהוי עטיפו עבור קוד אסינכרוני ) קטע קוד שרץ ברקע(‬ ‫•‬
‫‪ Promise‬ממש איך לחלץ ערך מסוים‬ ‫•‬
‫אחר כך יש לכתוב מה קורה כאשר ומקבלים את הערך‬ ‫•‬

‫• ‪ Promises‬מאפשרים להגדיר סדר עבור סידרה של פעולות שמתבצעות ברקע‬


‫• מצבים שונים של ‪:Promise‬‬
‫• ‪unresolved‬‬
‫• ‪succeeds‬‬
‫• ‪fails‬‬
Promise ‫כתיבת‬
• Basic syntax:
• do something (possibly asynchronous)
• when you get the result, call resolve() and pass the final result
• In case of error, call reject()
var p = new Promise( function(resolve,reject){
// do something, who knows how long it will take?
if (everythingOK) {
resolve (someStateToSave);
} else // same code using arrow functions
reject(Error(‘some error happened’); var p = new Promise((resolve,reject) => {
if (everythingOK) {
} resolve (someStateToSave);
}); } else
reject(Error(‘some error happened’);
}
});
Writing a Promise
• loadImage returns a promise to load a given image
function loadImage(url){
return new Promise(function(resolve, reject) {
var img = new Image();
img.src = url;
img.onload = function() { resolve(img) }
img.onerror = function(e) { reject(e) }
})’
}

• Once the image is loaded, we’ll resolve the promise


• If the image has an error, the promise is rejected
Using a Promise
• Just declare what you want to do when your promise is completed (then), or
if there’s an error (catch)
• The .then method specifies the action to perform when a promise is fulfilled
• The .catch method specifies what to do when promise is rejected

var imgPromise = loadImage("myimage.jpg");

imgPromise.then(function (img){
document.body.appendChild(img);
}).catch(function(e){ ‫יתרון‬
console.log(”error”:);
console.log(e);
‫• יותר קריא‬
}); ‫• ניתן לשרשר רצף של פעולות‬
Promising many things
‫ טעינת מספר תמונות‬:‫• דוגמא‬

Promise
.all([loadImage(”a.jpg"), loadImage(“b.jpg")]
.then(function (imgArray) {
imgArray.forEach(img => {document.body.appendChild(img)})

))
.catch(function (e) {
console.log(”error: "+ e);
});
Example
function multiply(a) {
console.log(a);
if (a > 16) throw `a is higher than 16`;
return Promise.resolve(a*a);
}
Promise.resolve(2) // Returns a fulfilled promise with value 2
.then(multiply) // console.log(2); Promise fulfilled, returns 4;
.then(multiply) // console.log(4); Promise fulfilled, returns 16
.then(multiply) // console.log(16); Promise fulfilled, returns 256
.then(multiply) // console.log(256); Promise rejected, throws `a is higher than 16`
.then(multiply) // not reached
.catch(error => {console.log(`Caught: ${error}`); return 3;}) //Catches error ‘a is higher than 16’ and returns 3
.then(multiply) // console.log(3); Promise fulfilled, returns 9
.then(console.log) //console.log(9); Promise fulfilled, returns void/undefined
Example: fetch weather from public API
const fetch = require('node-fetch’);
const lat = 37; const lon = 122; fetch(`http://www.7timer.info/bin/api.pl?lon=${lon}&lat=$
{lat}&product=astro&output=json`) .then(response => response.json()) //  1
.then(response => response.dataseries[0].temp2m) //  2
.then(temperature => console.log(`The temperature reported by the 7timer is: ${temperature} C`));

1. .json method reads the Response stream and returns a Promise with a JSON


object containing the data from the Response stream as its value. 
2. finds a specific data element in the JSON object and returns a Promise with the
retrieved data element as its value
3. A third .then method is applied to this promise chain to take the temperature
value and send it to standard output.

https://www.twilio.com/blog/asynchronous-javascript-advanced-promises-chaining-collections-nodejs
Chaining Promises
asyncThing1().then(function() {
  return asyncThing2();
}).then(function() {
  return asyncThing3();
}).catch(function(err) {
  return asyncRecovery1();
}).then(function() {
  return asyncThing4();
}, function(err) { ...‫במקום לכתוב‬
  return asyncRecovery2();
if (…) then {
}).catch(function(err) {
if (…) then {…
  console.log("Don't worry about it");
if (…) then { …
}).then(function() {
  console.log("All done!"); ‫ ואז ניתן לבנות ״שרשרת״ של‬Promise ‫מחזירים‬
}) asynchronous  ‫פעולות‬
Chaining example
const fetchData = () => {
const promise = new Promise((resolve, reject) => {
setTimeout(() => { ?‫ מה יהיה הפלט‬:‫שאלה‬
resolve('Done!');
}, 1500);
});
return promise; Output:
};
Hello!
setTimeout(() => {
Hi!
console.log('Timer is done!');
fetchData() Timer is done!
.then(text => {
console.log(text);
return fetchData(); Done!
}) Done!
.then(text2 => {
console.log(text2);
});
}, 2000);

console.log('Hello!');
console.log('Hi!');
Async/await
• The async command in Javascript is a shortcut to return a Promise
async function AsyncOk() {
// equivalent to :
// return Promise.resolve(’result');
return 'result';
}

AsyncOk().then(console.log) // log ”result"

async function AsyncErr() {


// // equivalent to :
// return Promise.reject(new Error('error'));
throw new Error('error');
}

AsyncErr().catch(err => console.log(err.message)) // log ”error"


Async/await
• Await is the “.then” of a Promise
• It allows to specify the code to execute after the Promise is resolved

• Conclusion: you can either use Promises or await/sync to write the


same code
• To convert Promise into async/await code:
• Add the keyword async to functions that return a Promise,
• replace the .then by await, and .catch by try/catch blocks
Web workers
(‫)נושא לא שייך לקורס – כדאי להכיר‬

• Web Workers allow you to run arbitrary code in the background,


without affecting the performance of your page
• Must be defined in separate files
• Can not access document, window, or parent objects (so no DOM
manipulation)
• Should mainly be used for performing long, intensive computation
(text parsing, image processing, big data)
• Communicate with the rest of your app with messages
Web Workers API
• Defining a new worker var worker = new Worker('worker.js');
• Registering a listener to hear results from the worker
worker.addEventListener("message", function(e){
console.log("Message from worker: <" + e.data + ">");
});
worker.addEventListener("error", function(e){
console.log(“Uh oh");
});
• Sending data to the worker
• worker.postMessage("Hello");
• In the worker: registering for messages from the main thread, sending responses
self.addEventListener('message', function(e) { doSomething(); }); self.postMessage(“Greetings from the
Worker");
• Including additional scripts:
importScripts('script2.js');
• Kill a worker:
worker.terminate();
Example
• Defining a web worker in worker.js
self.addEventListener('message', function(e) {
self.postMessage("Worker is sending back the text:" + e.data);
}, false);

• Using a web worker in our web app


<script language="javascript">
"use strict";
var worker = = new Worker('worker.js');
worker.addEventLsitener(“message”, function(e) {
console.log(“Message from worker: <“ + e.data + “>”);
});
worker.postMessage(“hello”);
worker.postMessage(“what’s up there?”);
worker.terminate();
</script>
When should you use workers?
• Mainly for computational stuff:
• Image manipulation
• Map routing (without going off to server)
• Numerical methods
• Remember: no access to the DOM!
References
• https://developers.google.com/web/fundamentals/primers/async-fun
ctions
• Code examples on course website
• https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_A
PI/Using_web_workers

• Requires registration:
• Book: Programming HTML5 Applications, Chapter 5, “Web Workers” (Safari
books online)
• Book: Javascript with Promises, Chapters 1-2 (Safari books online)

You might also like