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
PPTX
Avoiding Callback Hell with Async.js
PDF
Tech friday 22.01.2016
PDF
Asynchronous JavaScript Programming with Callbacks & Promises
PDF
Intro to Asynchronous Javascript
PPTX
webworkers
PPTX
From Web Developer to Hardware Developer
PPTX
Async Web QA
Callbacks and control flow in Node js
Avoiding Callback Hell with Async.js
Tech friday 22.01.2016
Asynchronous JavaScript Programming with Callbacks & Promises
Intro to Asynchronous Javascript
webworkers
From Web Developer to Hardware Developer
Async Web QA

What's hot (20)

PPTX
Nodejs intro
PDF
Callback Function
PDF
JavaScript Web Workers
PPTX
RxJS and Reactive Programming - Modern Web UI - May 2015
PDF
React on es6+
PDF
Breaking the Server-Client Divide with Node.js and React
PPTX
Node.js Patterns for Discerning Developers
PPTX
Accessing Mule variables in groovy
PPTX
Groovy example in mule
PDF
Brief Introduction on JavaScript - Internship Presentation - Week4
PPTX
Groovy in Mule
PPTX
Rethinking Best Practices
PDF
Workshop React.js
PPTX
Introduction to Node js
PDF
ReactJS
PDF
Unity and WebSockets
PPTX
What is Node.js
PDF
New feature of async fakeAsync test in angular
PDF
Real-time Web Application with Socket.IO, Node.js, and Redis
PPTX
Asynchronous Programming in ASP.NET
Nodejs intro
Callback Function
JavaScript Web Workers
RxJS and Reactive Programming - Modern Web UI - May 2015
React on es6+
Breaking the Server-Client Divide with Node.js and React
Node.js Patterns for Discerning Developers
Accessing Mule variables in groovy
Groovy example in mule
Brief Introduction on JavaScript - Internship Presentation - Week4
Groovy in Mule
Rethinking Best Practices
Workshop React.js
Introduction to Node js
ReactJS
Unity and WebSockets
What is Node.js
New feature of async fakeAsync test in angular
Real-time Web Application with Socket.IO, Node.js, and Redis
Asynchronous Programming in ASP.NET
Ad

Viewers also liked (14)

DOCX
Week%203%20 lab
PDF
Facilitating Discussions_workshop
PPTX
Textual Analysis
PPTX
What have you learnt about technologies from the process of constructing thi...
PPTX
Skyworks Presentation_Haley Large-Cap Fund
PDF
PPTX
Media studies work incomplete
PDF
Certificates and References
PPTX
Mi cas manual de autoconstruccion
PPTX
Skyworks
PPSX
An introduction to English phonetics
PPTX
I wanna go – britney spears
PPT
Nuclear fission
PPSX
Language skills & assessment
Week%203%20 lab
Facilitating Discussions_workshop
Textual Analysis
What have you learnt about technologies from the process of constructing thi...
Skyworks Presentation_Haley Large-Cap Fund
Media studies work incomplete
Certificates and References
Mi cas manual de autoconstruccion
Skyworks
An introduction to English phonetics
I wanna go – britney spears
Nuclear fission
Language skills & assessment
Ad

Similar to Asynchronous development in JavaScript (20)

PDF
Understanding Asynchronous JavaScript
PPTX
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
PPT
JSON Part 3: Asynchronous Ajax & JQuery Deferred
PDF
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
PPTX
JavaScript Multithread or Single Thread.pptx
PPTX
Avoiding callback hell in Node js using promises
PDF
Promises look into the async future
PDF
"Service Worker: Let Your Web App Feel Like a Native "
PDF
Developing Async Sense
PDF
Promises - Asynchronous Control Flow
PDF
Async js - Nemetschek Presentaion @ HackBulgaria
PPTX
Html web workers
ODP
Scala Future & Promises
PDF
Javascript internals
PPT
JS everywhere 2011
PDF
[2015/2016] JavaScript
PDF
The evolution of java script asynchronous calls
PPTX
JavaScript Engines and Event Loop
PDF
An opinionated intro to Node.js - devrupt hospitality hackathon
PPT
Extending Ajax Events for all mankind
Understanding Asynchronous JavaScript
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
JSON Part 3: Asynchronous Ajax & JQuery Deferred
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
JavaScript Multithread or Single Thread.pptx
Avoiding callback hell in Node js using promises
Promises look into the async future
"Service Worker: Let Your Web App Feel Like a Native "
Developing Async Sense
Promises - Asynchronous Control Flow
Async js - Nemetschek Presentaion @ HackBulgaria
Html web workers
Scala Future & Promises
Javascript internals
JS everywhere 2011
[2015/2016] JavaScript
The evolution of java script asynchronous calls
JavaScript Engines and Event Loop
An opinionated intro to Node.js - devrupt hospitality hackathon
Extending Ajax Events for all mankind

Recently uploaded (20)

PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PDF
Become an Agentblazer Champion Challenge Kickoff
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PPTX
Online Work Permit System for Fast Permit Processing
DOCX
The Five Best AI Cover Tools in 2025.docx
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Best Practices for Rolling Out Competency Management Software.pdf
PDF
Understanding Forklifts - TECH EHS Solution
PDF
The Role of Automation and AI in EHS Management for Data Centers.pdf
PDF
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
PDF
AI in Product Development-omnex systems
PPTX
Odoo POS Development Services by CandidRoot Solutions
PPT
Introduction Database Management System for Course Database
PPTX
L1 - Introduction to python Backend.pptx
PPTX
Transform Your Business with a Software ERP System
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
top salesforce developer skills in 2025.pdf
PDF
Digital Strategies for Manufacturing Companies
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
ManageIQ - Sprint 268 Review - Slide Deck
Become an Agentblazer Champion Challenge Kickoff
Which alternative to Crystal Reports is best for small or large businesses.pdf
Online Work Permit System for Fast Permit Processing
The Five Best AI Cover Tools in 2025.docx
Softaken Excel to vCard Converter Software.pdf
Best Practices for Rolling Out Competency Management Software.pdf
Understanding Forklifts - TECH EHS Solution
The Role of Automation and AI in EHS Management for Data Centers.pdf
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
AI in Product Development-omnex systems
Odoo POS Development Services by CandidRoot Solutions
Introduction Database Management System for Course Database
L1 - Introduction to python Backend.pptx
Transform Your Business with a Software ERP System
How Creative Agencies Leverage Project Management Software.pdf
top salesforce developer skills in 2025.pdf
Digital Strategies for Manufacturing Companies
PTS Company Brochure 2025 (1).pdf.......
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...

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