Professional Documents
Culture Documents
A Sync Programming
A Sync Programming
A Sync Programming
javascript-תכנות אסינכרוני ב
Internet Course
Dr Solange Karsenty
Hadasssah Academic College
תוכן
• מהו?asynchronous programming-
• מהו ?threads
• איך שומרים על דף אינטראקטיבי?
• כתיבת קוד אסינכרוני
למה ?Asynchronous
• לשמור על אינטרקציה עם המשתמש (הכוונה הדף לא קופא – קלט/פלט) ,כאשר בו
זמנית יש חישובים:
• עיבוד נתונים
• תקשרת עם שרת (לדוגמא טעינת בזמן אמת של תחזית מזג אוויר)
• טיימר שרץ ברקע (לדוגמא אנימציה)
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חייב לבדוק את מצב האפליקציה על מנת לדעת אם הטיפול עדיין רלוונטי
• דוגמא?
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`));
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';
}
• Requires registration:
• Book: Programming HTML5 Applications, Chapter 5, “Web Workers” (Safari
books online)
• Book: Javascript with Promises, Chapters 1-2 (Safari books online)