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

Introducing Async/Await
Introducing Async/AwaitIntroducing Async/Await
Introducing Async/Await
Valeri Karpov
 
JS Event Loop
JS Event LoopJS Event Loop
JS Event Loop
Saai Vignesh P
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
Derek Willian Stavis
 
3. Java Script
3. Java Script3. Java Script
3. Java Script
Jalpesh Vasa
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
boyney123
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
Aaron Gustafson
 
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
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
Bala Narayanan
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFuture
José Paumard
 
Typescript in React: HOW & WHY?
Typescript in React: HOW & WHY?Typescript in React: HOW & WHY?
Typescript in React: HOW & WHY?
Saulius Skeirys
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
Mindfire Solutions
 
Typescript ppt
Typescript pptTypescript ppt
Typescript ppt
akhilsreyas
 
What is component in reactjs
What is component in reactjsWhat is component in reactjs
What is component in reactjs
manojbkalla
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
Sehwan Noh
 
History of JavaScript
History of JavaScriptHistory of JavaScript
History of JavaScript
Rajat Saxena
 
Object Oriented Javascript
Object Oriented JavascriptObject Oriented Javascript
Object Oriented Javascript
NexThoughts Technologies
 
Introducing type script
Introducing type scriptIntroducing type script
Introducing type script
Remo Jansen
 
Intro to React
Intro to ReactIntro to React
Intro to React
Justin Reock
 
Javascript
JavascriptJavascript
Javascript
Nagarajan
 

What's hot (20)

Introducing Async/Await
Introducing Async/AwaitIntroducing Async/Await
Introducing Async/Await
 
JS Event Loop
JS Event LoopJS Event Loop
JS Event Loop
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
3. Java Script
3. Java Script3. Java Script
3. Java Script
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern Javascript
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFuture
 
Typescript in React: HOW & WHY?
Typescript in React: HOW & WHY?Typescript in React: HOW & WHY?
Typescript in React: HOW & WHY?
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
Typescript ppt
Typescript pptTypescript ppt
Typescript ppt
 
What is component in reactjs
What is component in reactjsWhat is component in reactjs
What is component in reactjs
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
History of JavaScript
History of JavaScriptHistory of JavaScript
History of JavaScript
 
Object Oriented Javascript
Object Oriented JavascriptObject Oriented Javascript
Object Oriented Javascript
 
Introducing type script
Introducing type scriptIntroducing type script
Introducing type script
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Javascript
JavascriptJavascript
Javascript
 

Similar to Asynchronous JavaScript Programming

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
 

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

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
 
What is new in PHP
What is new in PHPWhat is new in PHP
What is new in PHP
Haim 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.9
Haim Michael
 
Programming in Python on Steroid
Programming in Python on SteroidProgramming in Python on Steroid
Programming in Python on Steroid
Haim Michael
 
The matplotlib Library
The matplotlib LibraryThe matplotlib Library
The matplotlib Library
Haim Michael
 
Pandas meetup 20200908
Pandas meetup 20200908Pandas meetup 20200908
Pandas meetup 20200908
Haim Michael
 
The num py_library_20200818
The num py_library_20200818The num py_library_20200818
The num py_library_20200818
Haim Michael
 
Jupyter notebook 20200728
Jupyter notebook 20200728Jupyter notebook 20200728
Jupyter notebook 20200728
Haim Michael
 

More from Haim Michael (20)

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)
 
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
 

Recently uploaded

Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
Pro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp BookPro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp Book
abdulrafaychaudhry
 
Enterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptxEnterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptx
QuickwayInfoSystems3
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)
abdulrafaychaudhry
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 

Recently uploaded (20)

Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
Pro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp BookPro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp Book
 
Enterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptxEnterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptx
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 

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