SlideShare a Scribd company logo
1 of 53
Download to read offline
Asynchronous JS
Haim Michael
February 24th
, 2020
All logos, trade marks and brand names used in this presentation belong
to the respective owners.
lifemichael
© 1996-2018 All Rights Reserved.
Haim Michael Introduction
● Snowboarding. Learning. Coding. Teaching. More
than 18 years of Practical Experience.
lifemichael
© 1996-2018 All Rights Reserved.
Haim Michael Introduction
● Professional Certifications
Zend Certified Engineer in PHP
Certified Java Professional
Certified Java EE Web Component Developer
OMG Certified UML Professional
● MBA (cum laude) from Tel-Aviv University
Information Systems Management
lifemichael
© 2008 Haim Michael 20150805
Introduction
© 2008 Haim Michael
Introduction
 JavaScript is a single thread programming language that
provides us with asynchronous mechanism and multi
threading using web workers.
© 2008 Haim Michael
The Events Queue
 There is a queue of tasks the one and only thread needs to
complete.
© 2008 Haim Michael
The Events Queue First Demo
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Thread Block</title>
</head>
<body>
<script type="text/javascript">
var startTime = new Date();
setTimeout(function()
{
document.write("time passed is " +
(new Date() - startTime)+" ms");
}, 500);
while (new Date() - startTime < 3000) {};
</script>
</body>
</html>
© 2008 Haim Michael
The Events Queue First Demo
© 2008 Haim Michael
The Events Queue
 The one single thread and its events queue is the reason for
the unresponsiveness many web pages tend to show.
© 2008 Haim Michael
Asynchronous Functions
 When calling an asynchronous function in JavaScript we
expect it to return immediately and we expect it to call the
callback function we usually pass over (when it completes its
operation).
 When calling a synchronous function (the common case) we
expect it to return only when it completes its operation.
© 2008 Haim Michael
Asynchronous Functions
 In some cases we might encounter functions that might
behave either in a synchronous or in an asynchronous way.
One example is the $ function in jQuery. When passing it
another function that other function will be invoked when the
DOM loading completes. If the DOM was already loaded it will
be invoked immediately.
© 2008 Haim Michael
JavaScript Loading
 When using the simple script element tag as in the following
code sample the script will be loaded synchronously.
<script type="text/javascript" src=”lib.js”></script>
 Loading too many scripts using this script element in the
<head> part of the page might delay the rendering.
 Loading the scripts by putting the script elements in the end of
the <body> part might get us a static page with nonworking
controls.
© 2008 Haim Michael
JavaScript Loading
 When the script is called from code that belongs to the body
part of our page or when the script is responsible for the look
of our page then we better load it in the <head> element.
© 2008 Haim Michael
JavaScript Loading
 We can load our script programmatically either by using a
JavaScript library that was developed especially for that
purpose or by writing our own code.
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.src = 'mylib.js';
head.appendChild(script);
© 2008 Haim Michael
The requestIdleCallback Function
 Calling this function we should pass over the function we want
to be invoked in the background in those moments when the
one and only thread is free (not busy with other tasks).
© 2008 Haim Michael
The requestIdleCallback Function
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
function doInBackground() {
console.log("doing work in background");
}
if (window.requestIdleCallback) {
console.log("do in background is supported");
requestIdleCallback(doInBackground);
}
else {
setTimeout(doInBackground, 3);
}
</script>
</body>
</html>
© 2008 Haim Michael
The requestIdleCallback Function
© 2008 Haim Michael
Promises
© 2008 Haim Michael
Introduction
 ECMAScript 2015 provides us with the possibility to use
promises in our code.
 Promises allow us to to write code that executes
asynchronously. Promises allow us to write code that will be
executed at a later stage and if succeeded or failed a
notification will be generated accordingly.
 We can chain promises together based on success or failure
in a simpler easy to understand way.
© 2008 Haim Michael
Single Thread
 JavaScript has a single thread that handles a queue of jobs.
Whenever a new piece of code is ready to be executed it will
be added to the queue.
 When the JavaScript engine completes the execution of
specific job the event loop picks the next job in the queue and
executes it.
© 2008 Haim Michael
The Event Loop
 The event loop is a separated thread inside the JavaScript
engine.
 The event loop monitors the code execution and manages the
jobs queue. The jobs on that queue are executed according to
their order from the first job to the last one.
© 2008 Haim Michael
Events
 When a user clicks a button or presses a key on the keyboard
an event is triggered.
 The triggered event can be hooked with the code we want to
be executed whenever that event is triggered. The code we
hooked with the event will be added as a new job to the
queue.
© 2008 Haim Michael
Events
 The event handler code doesn’t execute until the event fires,
and when it does execute, it is executed as a separated job
that will be added to the queue and waits for its execution.
var button = document.getElementById("mybt");
button.onclick = function(event) {
console.log("click!");
};
© 2008 Haim Michael
The Callback Pattern
 The callback function is passed over as an argument. The
callback pattern makes it simple to chain multiple calls
together.
© 2008 Haim Michael
The Callback Pattern
func1("temp.txt", function(err, contents) {
if (err) {
console.log(“error...”)
}
func2("another.txt", function(err) {
if (err) {
console.log(“error...”)
}
});
});
© 2008 Haim Michael
Getting Location Sample
...
navigator.geolocation.getCurrentPosition(myfunc,myerrorfunc);
...
© 2008 Haim Michael
The Callback Hell Pattern
 When using the callback pattern and nesting too many
callbacks it can easily result in code that is hard to understand
and difficult to debug.
© 2008 Haim Michael
The Callback Hell Pattern
func1(function(err, result) {
if (err) {
console.log(“error...”);
}
func2(function(err, result) {
if (err) {
console.log(“error...”);
}
func3(function(err, result) {
if (err) {
console.log(“error...”);
}
func4(function(err, result) {
if (err) {
console.log(“error...”);
}
func5(result);
});
});
});
});
© 2008 Haim Michael
Problems of Higher Complexity
 When coping with problems of an higher complexity, such as
having two asynchronous operations running in parallel and
having another function we want to execute when the first two
completes.
© 2008 Haim Michael
Promise Basics
 Promise is an object that represents the result of an
asynchronous operation. Through the promise object it will be
possible to get the result of the asynchronous operation when
completed.
© 2008 Haim Michael
Promise Lifecycle
 Each and every promise goes through a short lifecycle. It
starts in the pending state (the asynchronous operation has
not yet completed).
 Once the asynchronous operation completes, the promise is
considered settled and enters one of two possible states.
Fulfilled (the asynchronous operation has completed
successfully) or Rejected (the asynchronous operation did not
complete successfully, due to some error or another cause).
© 2008 Haim Michael
Promise Lifecycle
 We can’t determine in which state the promise is in
programmatically.
 We can take a specific action when a promise changes state
by using the then() method.
 Each and every promise object has state property that is set
to "pending", "fulfilled", or "rejected" in order to reflect the
promise’s state.
© 2008 Haim Michael
The then Method
 The then() method is available on every promise object. It
takes two arguments. The first argument is a function to call
when the promise is fulfilled. The second argument is a
function to call when the promise is rejected.
 Both the fulfillment function and the rejection function are
passed over additional data related to the fulfillment or the
rejection (accordingly).
© 2008 Haim Michael
The Promise Constructor
 We can create new promises by calling the Promise function
constructor. The Promise function receives a single
argument, which is the function that contains the code to be
executed when the promise is added to the queue.
 The function we pass over to Promise should be with two
parameters that receive two functions as arguments. The
resolve() and the reject().
© 2008 Haim Michael
The Promise Constructor
 The resolve() function should be called when the executor
has finished successfully in order to signal that the promise is
ready to be resolved.
 The reject() function should be called when the executor
function fails and we want to indicate about it.
© 2008 Haim Michael
The Promise Constructor
var promise = new Promise(function(resolve, reject) {
document.write("<br/>promise was created!");
resolve();
});
promise.then(function() {
document.write("<br/>the promise's executor completed... then one!");
}).then(function() {
document.write("<br/>the promise's executor completed... then two!");
}).then(function() {
document.write("<br/>the promise's executor completed... then three!");
});
document.write("<br/>simple output!");
© 2008 Haim Michael
The Promise Constructor
© 2008 Haim Michael
The catch Method
 The catch() function is called when the executor
(represented by the promise object) fails. We should indicate
about that failure by calling the reject() function.
© 2008 Haim Michael
The catch Method
var promise = new Promise(function(resolve, reject) {
document.write("<br/>promise was created!");
//resolve();
reject();
});
promise.then(function() {
document.write("<br/>the promise's executor completed... then one!");
}).then(function() {
document.write("<br/>the promise's executor completed... then two!");
}).then(function() {
document.write("<br/>the promise's executor completed... then three!");
}).catch(function() {
document.write("<br/>inside catch");
});
document.write("<br/>simple output!");
© 2008 Haim Michael
Practical Code Sample
https://github.com/mdn/js-examples/blob/master/promises-test/index.html
Code Sample for Asynchronously Loading of Image using Ajax
© 2008 Haim Michael
The catch Method
© 2008 Haim Michael
The Fetch API
© 2008 Haim Michael
Introduction
 The Fetch API provides an interface for fetching resources,
whether on the network or not.
 The new Fetch API provides us with more capabilities
comparing with using the XmlHttpRequest object.
© 2008 Haim Michael
The Request and Response Objects
 The Fetch API provides us with a generic definition of
Request and Response objects.
© 2008 Haim Michael
The fetch Method
 The Fetch API provides us with a generic definition of
Request and Response objects.
 Calling this method we should pass over the URL for the
resource we want to fetch.
 The fetch method receives one mandatory argument. The
path to the resource we want to fetch.
© 2008 Haim Michael
The fetch Method
 The fetch method returns a Promise object that resolves to
the Response object. We will get the Response object in
any case. Whether the response was successful or not.
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Simple Code Sample for using The Fetch API
© 2008 Haim Michael
Simple Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
fetch('students.json')
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
});
</script>
</body>
</html>
© 2008 Haim Michael
Simple Demo
© 2008 Haim Michael
The async Keyword
© 2008 Haim Michael
Introduction
 Functions we mark with the async keyword are
asynchronous functions.
 Functions marked with the async keyword return an
AsyncFunction object, which is implicitly a Promise.
 When calling a function that returns AsyncFunction object
together with the await keyword we will get the
AsyncFunction only after its operation was completed.
© 2008 Haim Michael
Code Sample
function functionWith3SecondsDelay() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 3000);
});
}
async function asyncFunction() {
console.log('calling');
const result = await functionWith3SecondsDelay();
console.log("waiting completed");
console.log(result);
// expected output: 'resolved'
}
asyncFunction();
© 2008 Haim Michael
Code Sample
© 2009 Haim Michael All Rights Reserved 53
Questions & Answers
Thanks for Your Time!
Haim Michael
haim.michael@lifemichael.com
+972+3+3726013 ext:700
lifemichael

More Related Content

What's hot

What's hot (20)

Javascript
JavascriptJavascript
Javascript
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
Datatype in JavaScript
Datatype in JavaScriptDatatype in JavaScript
Datatype in JavaScript
 
Callback Function
Callback FunctionCallback Function
Callback Function
 
Async js
Async jsAsync js
Async js
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
JS Event Loop
JS Event LoopJS Event Loop
JS Event Loop
 
Express js
Express jsExpress js
Express js
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Javascript
JavascriptJavascript
Javascript
 
JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and Functions
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
What is Ajax technology?
What is Ajax technology?What is Ajax technology?
What is Ajax technology?
 
Javascript Basic
Javascript BasicJavascript Basic
Javascript Basic
 
Fetch API Talk
Fetch API TalkFetch API Talk
Fetch API Talk
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Service Worker Presentation
Service Worker PresentationService Worker Presentation
Service Worker Presentation
 
Jquery
JqueryJquery
Jquery
 
Form using html and java script validation
Form using html and java script validationForm using html and java script validation
Form using html and java script validation
 

Similar to Asynchronous JavaScript Programming

Java11 New Features
Java11 New FeaturesJava11 New Features
Java11 New FeaturesHaim Michael
 
jQuery basics
jQuery basicsjQuery basics
jQuery basicsKamal S
 
Node JS Crash Course
Node JS Crash CourseNode JS Crash Course
Node JS Crash CourseHaim Michael
 
Functional Programming in Python
Functional Programming in PythonFunctional Programming in Python
Functional Programming in PythonHaim Michael
 
Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start) Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start) Haim Michael
 
Functional programming in Java
Functional programming in Java  Functional programming in Java
Functional programming in Java Haim Michael
 
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav DukhinFwdays
 
Internet and Web Technology (CLASS-9) [React.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-9) [React.js] | NIC/NIELIT Web TechnologyInternet and Web Technology (CLASS-9) [React.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-9) [React.js] | NIC/NIELIT Web TechnologyAyes Chinmay
 
PHP7. Game Changer.
PHP7. Game Changer. PHP7. Game Changer.
PHP7. Game Changer. Haim Michael
 
Flex3 Deep Dive Final
Flex3 Deep Dive FinalFlex3 Deep Dive Final
Flex3 Deep Dive FinalRJ Owen
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]GDSC UofT Mississauga
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScriptAmitai Barnea
 

Similar to Asynchronous JavaScript Programming (20)

Java11 New Features
Java11 New FeaturesJava11 New Features
Java11 New Features
 
jQuery basics
jQuery basicsjQuery basics
jQuery basics
 
Node JS Crash Course
Node JS Crash CourseNode JS Crash Course
Node JS Crash Course
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
Functional Programming in Python
Functional Programming in PythonFunctional Programming in Python
Functional Programming in Python
 
Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start) Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start)
 
Functional programming in Java
Functional programming in Java  Functional programming in Java
Functional programming in Java
 
react-en.pdf
react-en.pdfreact-en.pdf
react-en.pdf
 
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
Internet and Web Technology (CLASS-9) [React.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-9) [React.js] | NIC/NIELIT Web TechnologyInternet and Web Technology (CLASS-9) [React.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-9) [React.js] | NIC/NIELIT Web Technology
 
PHP7. Game Changer.
PHP7. Game Changer. PHP7. Game Changer.
PHP7. Game Changer.
 
Flex3 Deep Dive Final
Flex3 Deep Dive FinalFlex3 Deep Dive Final
Flex3 Deep Dive Final
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
 
OneTeam Media Server
OneTeam Media ServerOneTeam Media Server
OneTeam Media Server
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
 
ASP.NET MVC3 RAD
ASP.NET MVC3 RADASP.NET MVC3 RAD
ASP.NET MVC3 RAD
 

More from Haim Michael

Virtual Threads in Java
Virtual Threads in JavaVirtual Threads in Java
Virtual Threads in JavaHaim Michael
 
MongoDB Design Patterns
MongoDB Design PatternsMongoDB Design Patterns
MongoDB Design PatternsHaim Michael
 
Introduction to SQL Injections
Introduction to SQL InjectionsIntroduction to SQL Injections
Introduction to SQL InjectionsHaim Michael
 
Record Classes in Java
Record Classes in JavaRecord Classes in Java
Record Classes in JavaHaim Michael
 
Microservices Design Patterns
Microservices Design PatternsMicroservices Design Patterns
Microservices Design PatternsHaim Michael
 
Structural Pattern Matching in Python
Structural Pattern Matching in PythonStructural Pattern Matching in Python
Structural Pattern Matching in PythonHaim Michael
 
Unit Testing in Python
Unit Testing in PythonUnit Testing in Python
Unit Testing in PythonHaim Michael
 
OOP Best Practices in JavaScript
OOP Best Practices in JavaScriptOOP Best Practices in JavaScript
OOP Best Practices in JavaScriptHaim Michael
 
JavaScript Jump Start 20220214
JavaScript Jump Start 20220214JavaScript Jump Start 20220214
JavaScript Jump Start 20220214Haim Michael
 
Bootstrap Jump Start
Bootstrap Jump StartBootstrap Jump Start
Bootstrap Jump StartHaim Michael
 
What is new in PHP
What is new in PHPWhat is new in PHP
What is new in PHPHaim Michael
 
What is new in Python 3.9
What is new in Python 3.9What is new in Python 3.9
What is new in Python 3.9Haim Michael
 
Programming in Python on Steroid
Programming in Python on SteroidProgramming in Python on Steroid
Programming in Python on SteroidHaim Michael
 
The matplotlib Library
The matplotlib LibraryThe matplotlib Library
The matplotlib LibraryHaim Michael
 
Pandas meetup 20200908
Pandas meetup 20200908Pandas meetup 20200908
Pandas meetup 20200908Haim Michael
 
The num py_library_20200818
The num py_library_20200818The num py_library_20200818
The num py_library_20200818Haim Michael
 
Jupyter notebook 20200728
Jupyter notebook 20200728Jupyter notebook 20200728
Jupyter notebook 20200728Haim Michael
 
The Power of Decorators in Python [Meetup]
The Power of Decorators in Python [Meetup]The Power of Decorators in Python [Meetup]
The Power of Decorators in Python [Meetup]Haim Michael
 

More from Haim Michael (20)

Anti Patterns
Anti PatternsAnti Patterns
Anti Patterns
 
Virtual Threads in Java
Virtual Threads in JavaVirtual Threads in Java
Virtual Threads in Java
 
MongoDB Design Patterns
MongoDB Design PatternsMongoDB Design Patterns
MongoDB Design Patterns
 
Introduction to SQL Injections
Introduction to SQL InjectionsIntroduction to SQL Injections
Introduction to SQL Injections
 
Record Classes in Java
Record Classes in JavaRecord Classes in Java
Record Classes in Java
 
Microservices Design Patterns
Microservices Design PatternsMicroservices Design Patterns
Microservices Design Patterns
 
Structural Pattern Matching in Python
Structural Pattern Matching in PythonStructural Pattern Matching in Python
Structural Pattern Matching in Python
 
Unit Testing in Python
Unit Testing in PythonUnit Testing in Python
Unit Testing in Python
 
OOP Best Practices in JavaScript
OOP Best Practices in JavaScriptOOP Best Practices in JavaScript
OOP Best Practices in JavaScript
 
Java Jump Start
Java Jump StartJava Jump Start
Java Jump Start
 
JavaScript Jump Start 20220214
JavaScript Jump Start 20220214JavaScript Jump Start 20220214
JavaScript Jump Start 20220214
 
Bootstrap Jump Start
Bootstrap Jump StartBootstrap Jump Start
Bootstrap Jump Start
 
What is new in PHP
What is new in PHPWhat is new in PHP
What is new in PHP
 
What is new in Python 3.9
What is new in Python 3.9What is new in Python 3.9
What is new in Python 3.9
 
Programming in Python on Steroid
Programming in Python on SteroidProgramming in Python on Steroid
Programming in Python on Steroid
 
The matplotlib Library
The matplotlib LibraryThe matplotlib Library
The matplotlib Library
 
Pandas meetup 20200908
Pandas meetup 20200908Pandas meetup 20200908
Pandas meetup 20200908
 
The num py_library_20200818
The num py_library_20200818The num py_library_20200818
The num py_library_20200818
 
Jupyter notebook 20200728
Jupyter notebook 20200728Jupyter notebook 20200728
Jupyter notebook 20200728
 
The Power of Decorators in Python [Meetup]
The Power of Decorators in Python [Meetup]The Power of Decorators in Python [Meetup]
The Power of Decorators in Python [Meetup]
 

Recently uploaded

Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineeringssuserb3a23b
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 

Recently uploaded (20)

Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineering
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 

Asynchronous JavaScript Programming

  • 1. Asynchronous JS Haim Michael February 24th , 2020 All logos, trade marks and brand names used in this presentation belong to the respective owners. lifemichael
  • 2. © 1996-2018 All Rights Reserved. Haim Michael Introduction ● Snowboarding. Learning. Coding. Teaching. More than 18 years of Practical Experience. lifemichael
  • 3. © 1996-2018 All Rights Reserved. Haim Michael Introduction ● Professional Certifications Zend Certified Engineer in PHP Certified Java Professional Certified Java EE Web Component Developer OMG Certified UML Professional ● MBA (cum laude) from Tel-Aviv University Information Systems Management lifemichael
  • 4. © 2008 Haim Michael 20150805 Introduction
  • 5. © 2008 Haim Michael Introduction  JavaScript is a single thread programming language that provides us with asynchronous mechanism and multi threading using web workers.
  • 6. © 2008 Haim Michael The Events Queue  There is a queue of tasks the one and only thread needs to complete.
  • 7. © 2008 Haim Michael The Events Queue First Demo <!DOCTYPE html> <html> <head> <title>JavaScript Thread Block</title> </head> <body> <script type="text/javascript"> var startTime = new Date(); setTimeout(function() { document.write("time passed is " + (new Date() - startTime)+" ms"); }, 500); while (new Date() - startTime < 3000) {}; </script> </body> </html>
  • 8. © 2008 Haim Michael The Events Queue First Demo
  • 9. © 2008 Haim Michael The Events Queue  The one single thread and its events queue is the reason for the unresponsiveness many web pages tend to show.
  • 10. © 2008 Haim Michael Asynchronous Functions  When calling an asynchronous function in JavaScript we expect it to return immediately and we expect it to call the callback function we usually pass over (when it completes its operation).  When calling a synchronous function (the common case) we expect it to return only when it completes its operation.
  • 11. © 2008 Haim Michael Asynchronous Functions  In some cases we might encounter functions that might behave either in a synchronous or in an asynchronous way. One example is the $ function in jQuery. When passing it another function that other function will be invoked when the DOM loading completes. If the DOM was already loaded it will be invoked immediately.
  • 12. © 2008 Haim Michael JavaScript Loading  When using the simple script element tag as in the following code sample the script will be loaded synchronously. <script type="text/javascript" src=”lib.js”></script>  Loading too many scripts using this script element in the <head> part of the page might delay the rendering.  Loading the scripts by putting the script elements in the end of the <body> part might get us a static page with nonworking controls.
  • 13. © 2008 Haim Michael JavaScript Loading  When the script is called from code that belongs to the body part of our page or when the script is responsible for the look of our page then we better load it in the <head> element.
  • 14. © 2008 Haim Michael JavaScript Loading  We can load our script programmatically either by using a JavaScript library that was developed especially for that purpose or by writing our own code. var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.src = 'mylib.js'; head.appendChild(script);
  • 15. © 2008 Haim Michael The requestIdleCallback Function  Calling this function we should pass over the function we want to be invoked in the background in those moments when the one and only thread is free (not busy with other tasks).
  • 16. © 2008 Haim Michael The requestIdleCallback Function <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script> function doInBackground() { console.log("doing work in background"); } if (window.requestIdleCallback) { console.log("do in background is supported"); requestIdleCallback(doInBackground); } else { setTimeout(doInBackground, 3); } </script> </body> </html>
  • 17. © 2008 Haim Michael The requestIdleCallback Function
  • 18. © 2008 Haim Michael Promises
  • 19. © 2008 Haim Michael Introduction  ECMAScript 2015 provides us with the possibility to use promises in our code.  Promises allow us to to write code that executes asynchronously. Promises allow us to write code that will be executed at a later stage and if succeeded or failed a notification will be generated accordingly.  We can chain promises together based on success or failure in a simpler easy to understand way.
  • 20. © 2008 Haim Michael Single Thread  JavaScript has a single thread that handles a queue of jobs. Whenever a new piece of code is ready to be executed it will be added to the queue.  When the JavaScript engine completes the execution of specific job the event loop picks the next job in the queue and executes it.
  • 21. © 2008 Haim Michael The Event Loop  The event loop is a separated thread inside the JavaScript engine.  The event loop monitors the code execution and manages the jobs queue. The jobs on that queue are executed according to their order from the first job to the last one.
  • 22. © 2008 Haim Michael Events  When a user clicks a button or presses a key on the keyboard an event is triggered.  The triggered event can be hooked with the code we want to be executed whenever that event is triggered. The code we hooked with the event will be added as a new job to the queue.
  • 23. © 2008 Haim Michael Events  The event handler code doesn’t execute until the event fires, and when it does execute, it is executed as a separated job that will be added to the queue and waits for its execution. var button = document.getElementById("mybt"); button.onclick = function(event) { console.log("click!"); };
  • 24. © 2008 Haim Michael The Callback Pattern  The callback function is passed over as an argument. The callback pattern makes it simple to chain multiple calls together.
  • 25. © 2008 Haim Michael The Callback Pattern func1("temp.txt", function(err, contents) { if (err) { console.log(“error...”) } func2("another.txt", function(err) { if (err) { console.log(“error...”) } }); });
  • 26. © 2008 Haim Michael Getting Location Sample ... navigator.geolocation.getCurrentPosition(myfunc,myerrorfunc); ...
  • 27. © 2008 Haim Michael The Callback Hell Pattern  When using the callback pattern and nesting too many callbacks it can easily result in code that is hard to understand and difficult to debug.
  • 28. © 2008 Haim Michael The Callback Hell Pattern func1(function(err, result) { if (err) { console.log(“error...”); } func2(function(err, result) { if (err) { console.log(“error...”); } func3(function(err, result) { if (err) { console.log(“error...”); } func4(function(err, result) { if (err) { console.log(“error...”); } func5(result); }); }); }); });
  • 29. © 2008 Haim Michael Problems of Higher Complexity  When coping with problems of an higher complexity, such as having two asynchronous operations running in parallel and having another function we want to execute when the first two completes.
  • 30. © 2008 Haim Michael Promise Basics  Promise is an object that represents the result of an asynchronous operation. Through the promise object it will be possible to get the result of the asynchronous operation when completed.
  • 31. © 2008 Haim Michael Promise Lifecycle  Each and every promise goes through a short lifecycle. It starts in the pending state (the asynchronous operation has not yet completed).  Once the asynchronous operation completes, the promise is considered settled and enters one of two possible states. Fulfilled (the asynchronous operation has completed successfully) or Rejected (the asynchronous operation did not complete successfully, due to some error or another cause).
  • 32. © 2008 Haim Michael Promise Lifecycle  We can’t determine in which state the promise is in programmatically.  We can take a specific action when a promise changes state by using the then() method.  Each and every promise object has state property that is set to "pending", "fulfilled", or "rejected" in order to reflect the promise’s state.
  • 33. © 2008 Haim Michael The then Method  The then() method is available on every promise object. It takes two arguments. The first argument is a function to call when the promise is fulfilled. The second argument is a function to call when the promise is rejected.  Both the fulfillment function and the rejection function are passed over additional data related to the fulfillment or the rejection (accordingly).
  • 34. © 2008 Haim Michael The Promise Constructor  We can create new promises by calling the Promise function constructor. The Promise function receives a single argument, which is the function that contains the code to be executed when the promise is added to the queue.  The function we pass over to Promise should be with two parameters that receive two functions as arguments. The resolve() and the reject().
  • 35. © 2008 Haim Michael The Promise Constructor  The resolve() function should be called when the executor has finished successfully in order to signal that the promise is ready to be resolved.  The reject() function should be called when the executor function fails and we want to indicate about it.
  • 36. © 2008 Haim Michael The Promise Constructor var promise = new Promise(function(resolve, reject) { document.write("<br/>promise was created!"); resolve(); }); promise.then(function() { document.write("<br/>the promise's executor completed... then one!"); }).then(function() { document.write("<br/>the promise's executor completed... then two!"); }).then(function() { document.write("<br/>the promise's executor completed... then three!"); }); document.write("<br/>simple output!");
  • 37. © 2008 Haim Michael The Promise Constructor
  • 38. © 2008 Haim Michael The catch Method  The catch() function is called when the executor (represented by the promise object) fails. We should indicate about that failure by calling the reject() function.
  • 39. © 2008 Haim Michael The catch Method var promise = new Promise(function(resolve, reject) { document.write("<br/>promise was created!"); //resolve(); reject(); }); promise.then(function() { document.write("<br/>the promise's executor completed... then one!"); }).then(function() { document.write("<br/>the promise's executor completed... then two!"); }).then(function() { document.write("<br/>the promise's executor completed... then three!"); }).catch(function() { document.write("<br/>inside catch"); }); document.write("<br/>simple output!");
  • 40. © 2008 Haim Michael Practical Code Sample https://github.com/mdn/js-examples/blob/master/promises-test/index.html Code Sample for Asynchronously Loading of Image using Ajax
  • 41. © 2008 Haim Michael The catch Method
  • 42. © 2008 Haim Michael The Fetch API
  • 43. © 2008 Haim Michael Introduction  The Fetch API provides an interface for fetching resources, whether on the network or not.  The new Fetch API provides us with more capabilities comparing with using the XmlHttpRequest object.
  • 44. © 2008 Haim Michael The Request and Response Objects  The Fetch API provides us with a generic definition of Request and Response objects.
  • 45. © 2008 Haim Michael The fetch Method  The Fetch API provides us with a generic definition of Request and Response objects.  Calling this method we should pass over the URL for the resource we want to fetch.  The fetch method receives one mandatory argument. The path to the resource we want to fetch.
  • 46. © 2008 Haim Michael The fetch Method  The fetch method returns a Promise object that resolves to the Response object. We will get the Response object in any case. Whether the response was successful or not. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch Simple Code Sample for using The Fetch API
  • 47. © 2008 Haim Michael Simple Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script> fetch('students.json') .then((response) => { return response.json(); }) .then((data) => { console.log(data); }); </script> </body> </html>
  • 48. © 2008 Haim Michael Simple Demo
  • 49. © 2008 Haim Michael The async Keyword
  • 50. © 2008 Haim Michael Introduction  Functions we mark with the async keyword are asynchronous functions.  Functions marked with the async keyword return an AsyncFunction object, which is implicitly a Promise.  When calling a function that returns AsyncFunction object together with the await keyword we will get the AsyncFunction only after its operation was completed.
  • 51. © 2008 Haim Michael Code Sample function functionWith3SecondsDelay() { return new Promise(resolve => { setTimeout(() => { resolve('resolved'); }, 3000); }); } async function asyncFunction() { console.log('calling'); const result = await functionWith3SecondsDelay(); console.log("waiting completed"); console.log(result); // expected output: 'resolved' } asyncFunction();
  • 52. © 2008 Haim Michael Code Sample
  • 53. © 2009 Haim Michael All Rights Reserved 53 Questions & Answers Thanks for Your Time! Haim Michael haim.michael@lifemichael.com +972+3+3726013 ext:700 lifemichael