SlideShare a Scribd company logo
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 (20)

React hooks
React hooksReact hooks
React hooks
Ramy ElBasyouni
 
TypeScript - An Introduction
TypeScript - An IntroductionTypeScript - An Introduction
TypeScript - An Introduction
NexThoughts Technologies
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
Minal Maniar
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
Derek Willian Stavis
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
ritika1
 
React JS - Introduction
React JS - IntroductionReact JS - Introduction
React JS - Introduction
Sergey Romaneko
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
Samundra khatri
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
L&T Technology Services Limited
 
ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern Javascript
Wojciech Dzikowski
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
DivyanshGupta922023
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfBasics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdf
Knoldus Inc.
 
React js
React jsReact js
React js
Oswald Campesato
 
Form Validation in JavaScript
Form Validation in JavaScriptForm Validation in JavaScript
Form Validation in JavaScript
Ravi Bhadauria
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
WebStackAcademy
 
TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the pain
Sander Mak (@Sander_Mak)
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 
javascript objects
javascript objectsjavascript objects
javascript objects
Vijay Kalyan
 
PHP Loops and PHP Forms
PHP  Loops and PHP FormsPHP  Loops and PHP Forms
PHP Loops and PHP Forms
M.Zalmai Rahmani
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
tanu_jaswal
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
Rob Eisenberg
 

Similar to Asynchronous JavaScript Programming (20)

JavaScript Promises Simplified [Free Meetup]
JavaScript Promises Simplified [Free Meetup]JavaScript Promises Simplified [Free Meetup]
JavaScript Promises Simplified [Free Meetup]
Haim Michael
 
Java11 New Features
Java11 New FeaturesJava11 New Features
Java11 New Features
Haim Michael
 
jQuery basics
jQuery basicsjQuery basics
jQuery basics
Kamal S
 
Node JS Crash Course
Node JS Crash CourseNode JS Crash Course
Node JS Crash Course
Haim Michael
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
Dominic Arrojado
 
Functional Programming in Python
Functional Programming in PythonFunctional Programming in Python
Functional Programming in Python
Haim 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
 
react-en.pdf
react-en.pdfreact-en.pdf
react-en.pdf
ssuser65180a
 
"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
Fwdays
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
Ivano Malavolta
 
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
Ayes 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 Final
RJ 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
 
JavaScript
JavaScriptJavaScript
JavaScript
Ivano Malavolta
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
Amitai Barnea
 
OneTeam Media Server
OneTeam Media ServerOneTeam Media Server
OneTeam Media Server
Mickaël Rémond
 
document object model in web technologies notes for engineering.pptx
document object model in web technologies notes for engineering.pptxdocument object model in web technologies notes for engineering.pptx
document object model in web technologies notes for engineering.pptx
manju451965
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
tutorialsruby
 
JavaScript Promises Simplified [Free Meetup]
JavaScript Promises Simplified [Free Meetup]JavaScript Promises Simplified [Free Meetup]
JavaScript Promises Simplified [Free Meetup]
Haim Michael
 
Java11 New Features
Java11 New FeaturesJava11 New Features
Java11 New Features
Haim Michael
 
jQuery basics
jQuery basicsjQuery basics
jQuery basics
Kamal S
 
Node JS Crash Course
Node JS Crash CourseNode JS Crash Course
Node JS Crash Course
Haim Michael
 
Functional Programming in Python
Functional Programming in PythonFunctional Programming in Python
Functional Programming in Python
Haim 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 Dukhin
Fwdays
 
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
Ayes 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 Final
RJ 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 JavaScript
Amitai Barnea
 
document object model in web technologies notes for engineering.pptx
document object model in web technologies notes for engineering.pptxdocument object model in web technologies notes for engineering.pptx
document object model in web technologies notes for engineering.pptx
manju451965
 
Ad

More from Haim Michael (20)

The Visitor Classic Design Pattern [Free Meetup]
The Visitor Classic Design Pattern [Free Meetup]The Visitor Classic Design Pattern [Free Meetup]
The Visitor Classic Design Pattern [Free Meetup]
Haim Michael
 
Typing in Python: Bringing Clarity, Safety and Speed to Your Code [Free Meetup]
Typing in Python: Bringing Clarity, Safety and Speed to Your Code [Free Meetup]Typing in Python: Bringing Clarity, Safety and Speed to Your Code [Free Meetup]
Typing in Python: Bringing Clarity, Safety and Speed to Your Code [Free Meetup]
Haim Michael
 
Introduction to Pattern Matching in Java [Free Meetup]
Introduction to Pattern Matching in Java [Free Meetup]Introduction to Pattern Matching in Java [Free Meetup]
Introduction to Pattern Matching in Java [Free Meetup]
Haim Michael
 
Mastering The Collections in JavaScript [Free Meetup]
Mastering The Collections in JavaScript [Free Meetup]Mastering The Collections in JavaScript [Free Meetup]
Mastering The Collections in JavaScript [Free Meetup]
Haim Michael
 
Beyond Java - Evolving to Scala and Kotlin
Beyond Java - Evolving to Scala and KotlinBeyond Java - Evolving to Scala and Kotlin
Beyond Java - Evolving to Scala and Kotlin
Haim Michael
 
Scala Jump Start [Free Online Meetup in English]
Scala Jump Start [Free Online Meetup in English]Scala Jump Start [Free Online Meetup in English]
Scala Jump Start [Free Online Meetup in English]
Haim Michael
 
The MVVM Architecture in Java [Free Meetup]
The MVVM Architecture in Java [Free Meetup]The MVVM Architecture in Java [Free Meetup]
The MVVM Architecture in Java [Free Meetup]
Haim Michael
 
Kotlin Jump Start Online Free Meetup (June 4th, 2024)
Kotlin Jump Start Online Free Meetup (June 4th, 2024)Kotlin Jump Start Online Free Meetup (June 4th, 2024)
Kotlin Jump Start Online Free Meetup (June 4th, 2024)
Haim Michael
 
Anti Patterns
Anti PatternsAnti Patterns
Anti Patterns
Haim Michael
 
Virtual Threads in Java
Virtual Threads in JavaVirtual Threads in Java
Virtual Threads in Java
Haim Michael
 
MongoDB Design Patterns
MongoDB Design PatternsMongoDB Design Patterns
MongoDB Design Patterns
Haim Michael
 
Introduction to SQL Injections
Introduction to SQL InjectionsIntroduction to SQL Injections
Introduction to SQL Injections
Haim Michael
 
Record Classes in Java
Record Classes in JavaRecord Classes in Java
Record Classes in Java
Haim Michael
 
Microservices Design Patterns
Microservices Design PatternsMicroservices Design Patterns
Microservices Design Patterns
Haim Michael
 
Structural Pattern Matching in Python
Structural Pattern Matching in PythonStructural Pattern Matching in Python
Structural Pattern Matching in Python
Haim Michael
 
Unit Testing in Python
Unit Testing in PythonUnit Testing in Python
Unit Testing in Python
Haim Michael
 
OOP Best Practices in JavaScript
OOP Best Practices in JavaScriptOOP Best Practices in JavaScript
OOP Best Practices in JavaScript
Haim Michael
 
Java Jump Start
Java Jump StartJava Jump Start
Java Jump Start
Haim Michael
 
JavaScript Jump Start 20220214
JavaScript Jump Start 20220214JavaScript Jump Start 20220214
JavaScript Jump Start 20220214
Haim Michael
 
Bootstrap Jump Start
Bootstrap Jump StartBootstrap Jump Start
Bootstrap Jump Start
Haim Michael
 
The Visitor Classic Design Pattern [Free Meetup]
The Visitor Classic Design Pattern [Free Meetup]The Visitor Classic Design Pattern [Free Meetup]
The Visitor Classic Design Pattern [Free Meetup]
Haim Michael
 
Typing in Python: Bringing Clarity, Safety and Speed to Your Code [Free Meetup]
Typing in Python: Bringing Clarity, Safety and Speed to Your Code [Free Meetup]Typing in Python: Bringing Clarity, Safety and Speed to Your Code [Free Meetup]
Typing in Python: Bringing Clarity, Safety and Speed to Your Code [Free Meetup]
Haim Michael
 
Introduction to Pattern Matching in Java [Free Meetup]
Introduction to Pattern Matching in Java [Free Meetup]Introduction to Pattern Matching in Java [Free Meetup]
Introduction to Pattern Matching in Java [Free Meetup]
Haim Michael
 
Mastering The Collections in JavaScript [Free Meetup]
Mastering The Collections in JavaScript [Free Meetup]Mastering The Collections in JavaScript [Free Meetup]
Mastering The Collections in JavaScript [Free Meetup]
Haim Michael
 
Beyond Java - Evolving to Scala and Kotlin
Beyond Java - Evolving to Scala and KotlinBeyond Java - Evolving to Scala and Kotlin
Beyond Java - Evolving to Scala and Kotlin
Haim Michael
 
Scala Jump Start [Free Online Meetup in English]
Scala Jump Start [Free Online Meetup in English]Scala Jump Start [Free Online Meetup in English]
Scala Jump Start [Free Online Meetup in English]
Haim Michael
 
The MVVM Architecture in Java [Free Meetup]
The MVVM Architecture in Java [Free Meetup]The MVVM Architecture in Java [Free Meetup]
The MVVM Architecture in Java [Free Meetup]
Haim Michael
 
Kotlin Jump Start Online Free Meetup (June 4th, 2024)
Kotlin Jump Start Online Free Meetup (June 4th, 2024)Kotlin Jump Start Online Free Meetup (June 4th, 2024)
Kotlin Jump Start Online Free Meetup (June 4th, 2024)
Haim Michael
 
Virtual Threads in Java
Virtual Threads in JavaVirtual Threads in Java
Virtual Threads in Java
Haim Michael
 
MongoDB Design Patterns
MongoDB Design PatternsMongoDB Design Patterns
MongoDB Design Patterns
Haim Michael
 
Introduction to SQL Injections
Introduction to SQL InjectionsIntroduction to SQL Injections
Introduction to SQL Injections
Haim Michael
 
Record Classes in Java
Record Classes in JavaRecord Classes in Java
Record Classes in Java
Haim Michael
 
Microservices Design Patterns
Microservices Design PatternsMicroservices Design Patterns
Microservices Design Patterns
Haim Michael
 
Structural Pattern Matching in Python
Structural Pattern Matching in PythonStructural Pattern Matching in Python
Structural Pattern Matching in Python
Haim Michael
 
Unit Testing in Python
Unit Testing in PythonUnit Testing in Python
Unit Testing in Python
Haim Michael
 
OOP Best Practices in JavaScript
OOP Best Practices in JavaScriptOOP Best Practices in JavaScript
OOP Best Practices in JavaScript
Haim Michael
 
JavaScript Jump Start 20220214
JavaScript Jump Start 20220214JavaScript Jump Start 20220214
JavaScript Jump Start 20220214
Haim Michael
 
Bootstrap Jump Start
Bootstrap Jump StartBootstrap Jump Start
Bootstrap Jump Start
Haim Michael
 
Ad

Recently uploaded (20)

Software Testing & it’s types (DevOps)
Software  Testing & it’s  types (DevOps)Software  Testing & it’s  types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
Migrating to Azure Cosmos DB the Right Way
Migrating to Azure Cosmos DB the Right WayMigrating to Azure Cosmos DB the Right Way
Migrating to Azure Cosmos DB the Right Way
Alexander (Alex) Komyagin
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
Key AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence CompaniesKey AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence Companies
Mypcot Infotech
 
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
WSO2
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricIntegration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Natan Silnitsky
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
dp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdfdp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdf
pravkumarbiz
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free DownloadWondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlowDevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI SearchAgentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Maxim Salnikov
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptxwAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
Software Testing & it’s types (DevOps)
Software  Testing & it’s  types (DevOps)Software  Testing & it’s  types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
Key AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence CompaniesKey AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence Companies
Mypcot Infotech
 
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
WSO2
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricIntegration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Natan Silnitsky
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
dp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdfdp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdf
pravkumarbiz
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free DownloadWondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlowDevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI SearchAgentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Maxim Salnikov
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptxwAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 

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 [email protected] +972+3+3726013 ext:700 lifemichael