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

PPTX
JS Event Loop
Saai Vignesh P
 
PDF
Intro to Asynchronous Javascript
Garrett Welson
 
PDF
Asynchronous JavaScript Programming with Callbacks & Promises
Hùng Nguyễn Huy
 
PPTX
Javascript functions
Alaref Abushaala
 
PDF
javascript objects
Vijay Kalyan
 
PPTX
JavaScript Event Loop
Designveloper
 
PPTX
Document Object Model (DOM)
GOPAL BASAK
 
JS Event Loop
Saai Vignesh P
 
Intro to Asynchronous Javascript
Garrett Welson
 
Asynchronous JavaScript Programming with Callbacks & Promises
Hùng Nguyễn Huy
 
Javascript functions
Alaref Abushaala
 
javascript objects
Vijay Kalyan
 
JavaScript Event Loop
Designveloper
 
Document Object Model (DOM)
GOPAL BASAK
 

What's hot (20)

PDF
The New JavaScript: ES6
Rob Eisenberg
 
PDF
Asynchronous javascript
Eman Mohamed
 
PPT
Java Script ppt
Priya Goyal
 
PPTX
JavaScript Promises
L&T Technology Services Limited
 
PPT
Javascript
mussawir20
 
PDF
Callback Function
Roland San Nicolas
 
PPTX
TypeScript Overview
Aniruddha Chakrabarti
 
PPTX
Modern JS with ES6
Kevin Langley Jr.
 
PDF
JavaScript guide 2020 Learn JavaScript
Laurence Svekis ✔
 
PDF
ES6 presentation
ritika1
 
PPT
Introduction to Javascript
Amit Tyagi
 
PPTX
Method overloading
Lovely Professional University
 
PPTX
Lab #2: Introduction to Javascript
Walid Ashraf
 
PDF
JavaScript - Chapter 4 - Types and Statements
WebStackAcademy
 
PPT
JavaScript & Dom Manipulation
Mohammed Arif
 
PPTX
Advanced JavaScript
Nascenia IT
 
PDF
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 
PPTX
Basic Concept of Node.js & NPM
Bhargav Anadkat
 
PPT
Js ppt
Rakhi Thota
 
PDF
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
The New JavaScript: ES6
Rob Eisenberg
 
Asynchronous javascript
Eman Mohamed
 
Java Script ppt
Priya Goyal
 
JavaScript Promises
L&T Technology Services Limited
 
Javascript
mussawir20
 
Callback Function
Roland San Nicolas
 
TypeScript Overview
Aniruddha Chakrabarti
 
Modern JS with ES6
Kevin Langley Jr.
 
JavaScript guide 2020 Learn JavaScript
Laurence Svekis ✔
 
ES6 presentation
ritika1
 
Introduction to Javascript
Amit Tyagi
 
Method overloading
Lovely Professional University
 
Lab #2: Introduction to Javascript
Walid Ashraf
 
JavaScript - Chapter 4 - Types and Statements
WebStackAcademy
 
JavaScript & Dom Manipulation
Mohammed Arif
 
Advanced JavaScript
Nascenia IT
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 
Basic Concept of Node.js & NPM
Bhargav Anadkat
 
Js ppt
Rakhi Thota
 
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
Ad

Similar to Asynchronous JavaScript Programming (20)

PDF
JavaScript Promises Simplified [Free Meetup]
Haim Michael
 
PPTX
Async discussion 9_29_15
Cheryl Yaeger
 
PDF
Asynchronous development in JavaScript
Amitai Barnea
 
PDF
The evolution of asynchronous javascript
Alessandro Cinelli (cirpo)
 
PDF
Understanding Asynchronous JavaScript
jnewmanux
 
PDF
Introduction to Node JS2.pdf
Bareen Shaikh
 
PPTX
Java Script Promise
Alok Guha
 
PDF
Javascript internals
Ayush Sharma
 
PPTX
Avoiding callback hell in Node js using promises
Ankit Agarwal
 
PDF
Avoiding callback hell with promises
TorontoNodeJS
 
PPTX
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola
 
PPTX
Async ... Await – concurrency in java script
Athman Gude
 
PDF
JavaScript, un langage plein de promesses
rfelden
 
PDF
Async History - javascript
Nishchit Dhanani
 
PDF
I'm Postal for Promises in Angular
Christian Lilley
 
PPTX
node.js workshop- JavaScript Async
Qiong Wu
 
PDF
4 mishchevskii - testing stage18-
Ievgenii Katsan
 
PDF
Event Driven Javascript
Federico Galassi
 
PPTX
asyncjavascript.pptxdgdsgdffgfdgfgfgfdgfdgf
zmulani8
 
PPTX
Avoiding Callback Hell with Async.js
cacois
 
JavaScript Promises Simplified [Free Meetup]
Haim Michael
 
Async discussion 9_29_15
Cheryl Yaeger
 
Asynchronous development in JavaScript
Amitai Barnea
 
The evolution of asynchronous javascript
Alessandro Cinelli (cirpo)
 
Understanding Asynchronous JavaScript
jnewmanux
 
Introduction to Node JS2.pdf
Bareen Shaikh
 
Java Script Promise
Alok Guha
 
Javascript internals
Ayush Sharma
 
Avoiding callback hell in Node js using promises
Ankit Agarwal
 
Avoiding callback hell with promises
TorontoNodeJS
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola
 
Async ... Await – concurrency in java script
Athman Gude
 
JavaScript, un langage plein de promesses
rfelden
 
Async History - javascript
Nishchit Dhanani
 
I'm Postal for Promises in Angular
Christian Lilley
 
node.js workshop- JavaScript Async
Qiong Wu
 
4 mishchevskii - testing stage18-
Ievgenii Katsan
 
Event Driven Javascript
Federico Galassi
 
asyncjavascript.pptxdgdsgdffgfdgfgfgfdgfdgf
zmulani8
 
Avoiding Callback Hell with Async.js
cacois
 
Ad

More from Haim Michael (20)

PDF
IntelliJ Debugging Essentials for Java Developers
Haim Michael
 
PDF
The Visitor Classic Design Pattern [Free Meetup]
Haim Michael
 
PDF
Typing in Python: Bringing Clarity, Safety and Speed to Your Code [Free Meetup]
Haim Michael
 
PDF
Introduction to Pattern Matching in Java [Free Meetup]
Haim Michael
 
PDF
Mastering The Collections in JavaScript [Free Meetup]
Haim Michael
 
PDF
Beyond Java - Evolving to Scala and Kotlin
Haim Michael
 
PDF
Scala Jump Start [Free Online Meetup in English]
Haim Michael
 
PDF
The MVVM Architecture in Java [Free Meetup]
Haim Michael
 
PDF
Kotlin Jump Start Online Free Meetup (June 4th, 2024)
Haim Michael
 
PDF
Anti Patterns
Haim Michael
 
PDF
Virtual Threads in Java
Haim Michael
 
PDF
MongoDB Design Patterns
Haim Michael
 
PDF
Introduction to SQL Injections
Haim Michael
 
PDF
Record Classes in Java
Haim Michael
 
PDF
Microservices Design Patterns
Haim Michael
 
PDF
Structural Pattern Matching in Python
Haim Michael
 
PDF
Unit Testing in Python
Haim Michael
 
PDF
OOP Best Practices in JavaScript
Haim Michael
 
PDF
Java Jump Start
Haim Michael
 
PDF
JavaScript Jump Start 20220214
Haim Michael
 
IntelliJ Debugging Essentials for Java Developers
Haim Michael
 
The Visitor Classic Design Pattern [Free Meetup]
Haim Michael
 
Typing in Python: Bringing Clarity, Safety and Speed to Your Code [Free Meetup]
Haim Michael
 
Introduction to Pattern Matching in Java [Free Meetup]
Haim Michael
 
Mastering The Collections in JavaScript [Free Meetup]
Haim Michael
 
Beyond Java - Evolving to Scala and Kotlin
Haim Michael
 
Scala Jump Start [Free Online Meetup in English]
Haim Michael
 
The MVVM Architecture in Java [Free Meetup]
Haim Michael
 
Kotlin Jump Start Online Free Meetup (June 4th, 2024)
Haim Michael
 
Anti Patterns
Haim Michael
 
Virtual Threads in Java
Haim Michael
 
MongoDB Design Patterns
Haim Michael
 
Introduction to SQL Injections
Haim Michael
 
Record Classes in Java
Haim Michael
 
Microservices Design Patterns
Haim Michael
 
Structural Pattern Matching in Python
Haim Michael
 
Unit Testing in Python
Haim Michael
 
OOP Best Practices in JavaScript
Haim Michael
 
Java Jump Start
Haim Michael
 
JavaScript Jump Start 20220214
Haim Michael
 

Recently uploaded (20)

DOCX
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
PDF
Adobe Illustrator Crack Full Download (Latest Version 2025) Pre-Activated
imang66g
 
PDF
Applitools Platform Pulse: What's New and What's Coming - July 2025
Applitools
 
PDF
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
PDF
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
PPTX
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
PDF
WatchTraderHub - Watch Dealer software with inventory management and multi-ch...
WatchDealer Pavel
 
PPTX
oapresentation.pptx
mehatdhavalrajubhai
 
PDF
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
PPTX
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
PPTX
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
PDF
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
ESUG
 
PDF
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
PDF
vAdobe Premiere Pro 2025 (v25.2.3.004) Crack Pre-Activated Latest
imang66g
 
PDF
New Download MiniTool Partition Wizard Crack Latest Version 2025
imang66g
 
PPTX
Explanation about Structures in C language.pptx
Veeral Rathod
 
PPTX
Can You Build Dashboards Using Open Source Visualization Tool.pptx
Varsha Nayak
 
PDF
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
PPTX
Presentation about variables and constant.pptx
kr2589474
 
PDF
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
Adobe Illustrator Crack Full Download (Latest Version 2025) Pre-Activated
imang66g
 
Applitools Platform Pulse: What's New and What's Coming - July 2025
Applitools
 
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
WatchTraderHub - Watch Dealer software with inventory management and multi-ch...
WatchDealer Pavel
 
oapresentation.pptx
mehatdhavalrajubhai
 
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
ESUG
 
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
vAdobe Premiere Pro 2025 (v25.2.3.004) Crack Pre-Activated Latest
imang66g
 
New Download MiniTool Partition Wizard Crack Latest Version 2025
imang66g
 
Explanation about Structures in C language.pptx
Veeral Rathod
 
Can You Build Dashboards Using Open Source Visualization Tool.pptx
Varsha Nayak
 
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
Presentation about variables and constant.pptx
kr2589474
 
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 

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