SlideShare a Scribd company logo
Asynchronous development
in JavaScript
Why?
Performance
responsiveness
When?
Long running operations
Calculation
Network
File access
JavaScript vs Other Languages
C++, Java, C#
-- Multiple threads
JavaScript
-- Single threaded
-- Uses event driven programming model
The Event Loop
The web browser trigger events, such as mouse
events, keyboard events DOM events, etc.
The event is queued into the event loop.
Each time, the JavaScript thread takes the next
event and execute it.
When it nish to handle the event, it takes the
next one.
JavaScript does one thing at a time?
The browser expose a set of asynchronous
functionalities.
The commons are network operation such as
HTTP requests, local storage operations etc.
The web browser uses a C++ libraries (Usually)
that uses threads and run the “long running”
operation on them.
When the operation is over it will trigger an event
(success or failure).
The browser (through the event loop) will execute
the attached functionality.
Callback
Asynchronous objects allow to attach a callback to
the execution of the function.
The callback is a function that will be called as the
operation ended.
Implementation of a callback looks like this:
function AsyncCall(callback) {
// create the async object
var worker = new worker();
// register on the 'finish' event
worker.onfinish = function() {
// run the callback
callback(worker.response);
}
// run the workload
worker.doWork();
};
asyncCall(function(){
alert(“finish!);
});
Callback hell
Using callbacks can caused a different type of
problem:
Assuming we need to do a series of operations.
Each operation depends on the success of its
previous.
The code can become messy.
Reviewing, debugging and xing the code had
become a very hard thing to do.
Our code will look like a spaghetti:
asyncCall(function(response) {
If (response.status == 200) {
calculateResult(function(result) {
If(result.status == OK) {
loadFile(function(res) {
If(res == success) {
doSomthing();
} else { alert(“file error”) }
}
}
else {
alert(calculation error”)
}
} else {
alert(“API error”)
}
}
}
Promises
Promises
Promise is a javascript object that is used for
deferred and asynchronous computations. A
Promise represents an operation that hasn't
completed yet, but is expected in the future.
Promises is a pattern that exists in the web
development for a long time. You can nd it in Q or
in JQuery deffered, and more.
In ECMA6 (ES2016), it has become a of cially a
part of javascript. The standard for JavaScript
Promises is called Promises/A+.
Creation of a promise:
var promise = new Promise(function(resolve, reject) {
doTheWork();
if (response == success) {
resolve(response);
} else {
reject(response)
}
Usage of a promise
promise.then(function(result){
alert("success");
}, function(result) {
alert("failed");
})
So much cleaner!
Promises states
pending: initial state, not ful lled or rejected.
ful lled: meaning that the operation completed
successfully.
rejected: meaning that the operation failed.
It can only succeed ones or rejected once.
Cascading and multiplicity
Another great feature of Promise is cascading.
Promise enables to connect promises one after the
other.
promise.then(function(result){
// success
}, function(result) {
//failure
}).then(..).then(...).
Error handling
promise.then(..).then(..).then(...).catch(...)
multiple promises
Promise.all([promise1, promise2, promise3] )
.then(function(results){
})
Async/Await
Async/Await
ES7 Async new feature
Write asynchronous as synchronous
async function foo() {
let x = await doWork();
console.log(x);
}
Async/Await Error Handling
Just like synchronous code
async function foo() {
try {
let x = await doWork();
console.log(x);
} catch (err) {
console.log(err);
}
}
Web Workers
Web workers
Allows running a code in the background.
The code actually runs on a separate thread
allowing true concurrency.
Useful for running long scripts without blocking
the application.
Web workers restrictions:
-- Not being allowed to access the DOM.
-- Communicate with one another by messaging.
Web workers on practice
Creating a worker:
var worker = new Worker("worker.js");
Activate it by sending it messages:
worker.postMessage(“DoSomething!”);
The worker code:
onmessage = function (e) {
var response = doMyWork(e.data);
// response back to caller
postMessage(response);}
Registration to the worker:
worker.onmessage(function (e) {
var message = e.data
alert(“worker says: “ + message);
}
Like promises, the worker enables to get an error:
worker.onerror = function(e) {
var error= e.data
alert(“worker had an error: “ + error);
}
Worker termination
There are two ways to terminate a worker, from
inside:
close();
Or from the creator of the worker:
worker.close();
Thank You
@AmitaiBarnea
https://github.com/amitai10/js-async-examples

More Related Content

PDF
Callbacks and control flow in Node js
Thomas Roch
 
PPTX
Avoiding Callback Hell with Async.js
cacois
 
PDF
Tech friday 22.01.2016
Poutapilvi Web Design
 
PDF
Asynchronous JavaScript Programming with Callbacks & Promises
Hùng Nguyễn Huy
 
PDF
Intro to Asynchronous Javascript
Garrett Welson
 
PPTX
webworkers
Asanka Indrajith
 
PPTX
From Web Developer to Hardware Developer
alexshenoy
 
PPTX
Async Web QA
Vlad Maniak
 
Callbacks and control flow in Node js
Thomas Roch
 
Avoiding Callback Hell with Async.js
cacois
 
Tech friday 22.01.2016
Poutapilvi Web Design
 
Asynchronous JavaScript Programming with Callbacks & Promises
Hùng Nguyễn Huy
 
Intro to Asynchronous Javascript
Garrett Welson
 
webworkers
Asanka Indrajith
 
From Web Developer to Hardware Developer
alexshenoy
 
Async Web QA
Vlad Maniak
 

What's hot (20)

PPTX
Nodejs intro
Ndjido Ardo BAR
 
PDF
Callback Function
Roland San Nicolas
 
PDF
JavaScript Web Workers
Tobias Pfeiffer
 
PPTX
RxJS and Reactive Programming - Modern Web UI - May 2015
Ben Lesh
 
PDF
React on es6+
Nikolaus Graf
 
PDF
Breaking the Server-Client Divide with Node.js and React
Dejan Glozic
 
PPTX
Node.js Patterns for Discerning Developers
cacois
 
PPTX
Accessing Mule variables in groovy
Anirban Sen Chowdhary
 
PPTX
Groovy example in mule
Mohammed246
 
PDF
Brief Introduction on JavaScript - Internship Presentation - Week4
Devang Garach
 
PPTX
Groovy in Mule
Praneethchampion
 
PPTX
Rethinking Best Practices
floydophone
 
PDF
Workshop React.js
Commit University
 
PPTX
Introduction to Node js
Akshay Mathur
 
PDF
ReactJS
Kamlesh Singh
 
PDF
Unity and WebSockets
Josh Glover
 
PPTX
What is Node.js
mohamed hadrich
 
PDF
New feature of async fakeAsync test in angular
Jia Li
 
PDF
Real-time Web Application with Socket.IO, Node.js, and Redis
York Tsai
 
PPTX
Asynchronous Programming in ASP.NET
Chris Dufour
 
Nodejs intro
Ndjido Ardo BAR
 
Callback Function
Roland San Nicolas
 
JavaScript Web Workers
Tobias Pfeiffer
 
RxJS and Reactive Programming - Modern Web UI - May 2015
Ben Lesh
 
React on es6+
Nikolaus Graf
 
Breaking the Server-Client Divide with Node.js and React
Dejan Glozic
 
Node.js Patterns for Discerning Developers
cacois
 
Accessing Mule variables in groovy
Anirban Sen Chowdhary
 
Groovy example in mule
Mohammed246
 
Brief Introduction on JavaScript - Internship Presentation - Week4
Devang Garach
 
Groovy in Mule
Praneethchampion
 
Rethinking Best Practices
floydophone
 
Workshop React.js
Commit University
 
Introduction to Node js
Akshay Mathur
 
ReactJS
Kamlesh Singh
 
Unity and WebSockets
Josh Glover
 
What is Node.js
mohamed hadrich
 
New feature of async fakeAsync test in angular
Jia Li
 
Real-time Web Application with Socket.IO, Node.js, and Redis
York Tsai
 
Asynchronous Programming in ASP.NET
Chris Dufour
 
Ad

Viewers also liked (14)

DOCX
Week%203%20 lab
Cliff Hunt
 
PDF
Facilitating Discussions_workshop
Vicki Stieha
 
PPTX
Textual Analysis
tgtwgdsh
 
PPTX
What have you learnt about technologies from the process of constructing thi...
tgtwgdsh
 
PPTX
Skyworks Presentation_Haley Large-Cap Fund
Thao P Le
 
PDF
React
Amitai Barnea
 
PPTX
Media studies work incomplete
tgtwgdsh
 
PDF
Certificates and References
Maxson Walai Sangai
 
PPTX
Mi cas manual de autoconstruccion
MichelleRios0509
 
PPTX
Skyworks
Thao P Le
 
PPSX
An introduction to English phonetics
Nasrin Eftekhary
 
PPTX
I wanna go – britney spears
tgtwgdsh
 
PPT
Nuclear fission
Anu Ashokan
 
PPSX
Language skills & assessment
Nasrin Eftekhary
 
Week%203%20 lab
Cliff Hunt
 
Facilitating Discussions_workshop
Vicki Stieha
 
Textual Analysis
tgtwgdsh
 
What have you learnt about technologies from the process of constructing thi...
tgtwgdsh
 
Skyworks Presentation_Haley Large-Cap Fund
Thao P Le
 
Media studies work incomplete
tgtwgdsh
 
Certificates and References
Maxson Walai Sangai
 
Mi cas manual de autoconstruccion
MichelleRios0509
 
Skyworks
Thao P Le
 
An introduction to English phonetics
Nasrin Eftekhary
 
I wanna go – britney spears
tgtwgdsh
 
Nuclear fission
Anu Ashokan
 
Language skills & assessment
Nasrin Eftekhary
 
Ad

Similar to Asynchronous development in JavaScript (20)

PDF
Understanding Asynchronous JavaScript
jnewmanux
 
PPTX
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
PROIDEA
 
PPT
JSON Part 3: Asynchronous Ajax & JQuery Deferred
Jeff Fox
 
PDF
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
GITS Indonesia
 
PPTX
JavaScript Multithread or Single Thread.pptx
RAHITNATH
 
PPTX
Avoiding callback hell in Node js using promises
Ankit Agarwal
 
PDF
Promises look into the async future
slicejs
 
PDF
"Service Worker: Let Your Web App Feel Like a Native "
FDConf
 
PDF
Developing Async Sense
Nemanja Stojanovic
 
PDF
Promises - Asynchronous Control Flow
Henrique Barcelos
 
PDF
Async js - Nemetschek Presentaion @ HackBulgaria
HackBulgaria
 
PPTX
Html web workers
AbhishekMondal42
 
ODP
Scala Future & Promises
Knoldus Inc.
 
PDF
Javascript internals
Ayush Sharma
 
PPT
JS everywhere 2011
Oleg Podsechin
 
PDF
[2015/2016] JavaScript
Ivano Malavolta
 
PDF
The evolution of java script asynchronous calls
Huy Hoàng Phạm
 
PPTX
JavaScript Engines and Event Loop
Tapan B.K.
 
PDF
An opinionated intro to Node.js - devrupt hospitality hackathon
Luciano Mammino
 
PPT
Extending Ajax Events for all mankind
Kyle Simpson
 
Understanding Asynchronous JavaScript
jnewmanux
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
PROIDEA
 
JSON Part 3: Asynchronous Ajax & JQuery Deferred
Jeff Fox
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
GITS Indonesia
 
JavaScript Multithread or Single Thread.pptx
RAHITNATH
 
Avoiding callback hell in Node js using promises
Ankit Agarwal
 
Promises look into the async future
slicejs
 
"Service Worker: Let Your Web App Feel Like a Native "
FDConf
 
Developing Async Sense
Nemanja Stojanovic
 
Promises - Asynchronous Control Flow
Henrique Barcelos
 
Async js - Nemetschek Presentaion @ HackBulgaria
HackBulgaria
 
Html web workers
AbhishekMondal42
 
Scala Future & Promises
Knoldus Inc.
 
Javascript internals
Ayush Sharma
 
JS everywhere 2011
Oleg Podsechin
 
[2015/2016] JavaScript
Ivano Malavolta
 
The evolution of java script asynchronous calls
Huy Hoàng Phạm
 
JavaScript Engines and Event Loop
Tapan B.K.
 
An opinionated intro to Node.js - devrupt hospitality hackathon
Luciano Mammino
 
Extending Ajax Events for all mankind
Kyle Simpson
 

Recently uploaded (20)

PDF
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
PDF
Salesforce Implementation Services Provider.pdf
VALiNTRY360
 
PDF
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
PPTX
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
PPTX
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
PDF
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
PDF
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
PPTX
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pptx
Certivo Inc
 
PPTX
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
PDF
Build Multi-agent using Agent Development Kit
FadyIbrahim23
 
PDF
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
PPT
Activate_Methodology_Summary presentatio
annapureddyn
 
PPTX
oapresentation.pptx
mehatdhavalrajubhai
 
PDF
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
Hironori Washizaki
 
PPT
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
PPTX
Smart Panchayat Raj e-Governance App.pptx
Rohitnikam33
 
PPTX
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
PDF
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
PPTX
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
DOCX
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
Salesforce Implementation Services Provider.pdf
VALiNTRY360
 
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pptx
Certivo Inc
 
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
Build Multi-agent using Agent Development Kit
FadyIbrahim23
 
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
Activate_Methodology_Summary presentatio
annapureddyn
 
oapresentation.pptx
mehatdhavalrajubhai
 
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
Hironori Washizaki
 
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
Smart Panchayat Raj e-Governance App.pptx
Rohitnikam33
 
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 

Asynchronous development in JavaScript

  • 3. JavaScript vs Other Languages C++, Java, C# -- Multiple threads JavaScript -- Single threaded -- Uses event driven programming model
  • 4. The Event Loop The web browser trigger events, such as mouse events, keyboard events DOM events, etc. The event is queued into the event loop. Each time, the JavaScript thread takes the next event and execute it. When it nish to handle the event, it takes the next one.
  • 5. JavaScript does one thing at a time? The browser expose a set of asynchronous functionalities. The commons are network operation such as HTTP requests, local storage operations etc. The web browser uses a C++ libraries (Usually) that uses threads and run the “long running” operation on them. When the operation is over it will trigger an event (success or failure). The browser (through the event loop) will execute the attached functionality.
  • 6. Callback Asynchronous objects allow to attach a callback to the execution of the function. The callback is a function that will be called as the operation ended.
  • 7. Implementation of a callback looks like this: function AsyncCall(callback) { // create the async object var worker = new worker(); // register on the 'finish' event worker.onfinish = function() { // run the callback callback(worker.response); } // run the workload worker.doWork(); }; asyncCall(function(){ alert(“finish!); });
  • 8. Callback hell Using callbacks can caused a different type of problem: Assuming we need to do a series of operations. Each operation depends on the success of its previous. The code can become messy. Reviewing, debugging and xing the code had become a very hard thing to do.
  • 9. Our code will look like a spaghetti: asyncCall(function(response) { If (response.status == 200) { calculateResult(function(result) { If(result.status == OK) { loadFile(function(res) { If(res == success) { doSomthing(); } else { alert(“file error”) } } } else { alert(calculation error”) } } else { alert(“API error”) } } }
  • 11. Promises Promise is a javascript object that is used for deferred and asynchronous computations. A Promise represents an operation that hasn't completed yet, but is expected in the future. Promises is a pattern that exists in the web development for a long time. You can nd it in Q or in JQuery deffered, and more. In ECMA6 (ES2016), it has become a of cially a part of javascript. The standard for JavaScript Promises is called Promises/A+.
  • 12. Creation of a promise: var promise = new Promise(function(resolve, reject) { doTheWork(); if (response == success) { resolve(response); } else { reject(response) }
  • 13. Usage of a promise promise.then(function(result){ alert("success"); }, function(result) { alert("failed"); }) So much cleaner!
  • 14. Promises states pending: initial state, not ful lled or rejected. ful lled: meaning that the operation completed successfully. rejected: meaning that the operation failed. It can only succeed ones or rejected once.
  • 15. Cascading and multiplicity Another great feature of Promise is cascading. Promise enables to connect promises one after the other. promise.then(function(result){ // success }, function(result) { //failure }).then(..).then(...).
  • 18. Async/Await ES7 Async new feature Write asynchronous as synchronous async function foo() { let x = await doWork(); console.log(x); }
  • 19. Async/Await Error Handling Just like synchronous code async function foo() { try { let x = await doWork(); console.log(x); } catch (err) { console.log(err); } }
  • 21. Web workers Allows running a code in the background. The code actually runs on a separate thread allowing true concurrency. Useful for running long scripts without blocking the application. Web workers restrictions: -- Not being allowed to access the DOM. -- Communicate with one another by messaging.
  • 22. Web workers on practice Creating a worker: var worker = new Worker("worker.js"); Activate it by sending it messages: worker.postMessage(“DoSomething!”); The worker code: onmessage = function (e) { var response = doMyWork(e.data); // response back to caller postMessage(response);}
  • 23. Registration to the worker: worker.onmessage(function (e) { var message = e.data alert(“worker says: “ + message); } Like promises, the worker enables to get an error: worker.onerror = function(e) { var error= e.data alert(“worker had an error: “ + error); }
  • 24. Worker termination There are two ways to terminate a worker, from inside: close(); Or from the creator of the worker: worker.close();