SlideShare a Scribd company logo
Async
JavaScript and
Promises
Sunday, 25 August 13
Callbacks
console.log("Before	
  readFile");
fs.readFile("file1.txt",	
  function(file1Content)	
  {
	
  	
  console.log("File	
  Contents	
  here");
	
  	
  return	
  "#"	
  +	
  file1Content	
  +	
  "#";
});
console.log("After	
  readFile");
Functions are first class citizens in JavaScript
Functions can takes functions as argument and call
them when they are done
Sunday, 25 August 13
Callbacks
console.log("Before	
  readFile");
fs.readFile("file1.txt",	
  function(file1Content)	
  {
	
  	
  console.log("File	
  Contents	
  here");
	
  	
  return	
  "#"	
  +	
  file1Content	
  +	
  "#";
});
console.log("After	
  readFile");
Functions are first class citizens in JavaScript
Functions can takes functions as argument and call
them when they are done
Sunday, 25 August 13
Is JavaScript really
Async?
All of the JavaScript engines including V8
are single-threaded
But all I/O is evented and asynchronous
It is possible via the EventLoop
Sunday, 25 August 13
An entity that handles and processes external
events and converts them into callback
invocations
Every asynchronous operation adds itself to
the EventLoop
Event Loops
Sunday, 25 August 13
How EventLoop
works?
Sunday, 25 August 13
Event Loop
Sunday, 25 August 13
Making Code
Asynchronous
setImmediate
process.nextTick
setTimeout / setInterval
Sunday, 25 August 13
Promises
A Promise is an object that represents a one-time
event, typically the outcome of an async task like an
AJAX call.
At first, a Promise is in a pending state. Eventually,
it’s either resolved or rejected.
Once a Promise is resolved or rejected, it’ll remain in
that state forever, and its callbacks will never fire
again.
Sunday, 25 August 13
What are
Promises For?
Sunday, 25 August 13
Callback Hell
step1(function	
  (value1)	
  {
	
  	
  step2(value1,	
  function(value2)	
  {
	
  	
  	
  	
  step3(value2,	
  function(value3)	
  {
	
  	
  	
  	
  	
  	
  step4(value3,	
  function(value4)	
  {
	
  	
  	
  	
  	
  	
  	
  	
  //	
  Do	
  something	
  with	
  value4
	
  	
  	
  	
  	
  	
  });
	
  	
  	
  	
  });
	
  	
  });
});
Q.fcall(promisedStep1)
.then(promisedStep2)
.then(promisedStep3)
.then(promisedStep4)
.then(function	
  (value4)	
  {
	
  	
  	
  	
  //	
  Do	
  something	
  with	
  value4
})
.done();
Promises can solve the problem of “Callback Hell”
Sunday, 25 August 13
Handling exceptions
Promises also helps you handle exceptions in a cleaner way
var	
  handleError	
  =	
  console.log;
step1(function	
  (value1)	
  {
	
  	
  step2(value1,	
  function(value2)	
  {
	
  	
  	
  	
  step3(value2,	
  function(value3)	
  {
	
  	
  	
  	
  	
  	
  step4(value3,	
  function(value4)	
  {
	
  	
  	
  	
  	
  	
  	
  	
  //	
  Do	
  something	
  with	
  value4
	
  	
  	
  	
  	
  	
  },	
  handleError);
	
  	
  	
  	
  },	
  handleError);
	
  	
  },	
  handleError);
},	
  handleError);
Q.fcall(promisedStep1)
.then(promisedStep2)
.then(promisedStep3)
.then(promisedStep4)
.then(function(value4)	
  {
	
  	
  	
  	
  //	
  Do	
  something	
  with	
  value4
})
.fail(function(error)	
  {
	
  	
  	
  	
  //	
  Handle	
  any	
  error	
  from	
  all	
  above	
  
steps
})
.done();
Sunday, 25 August 13
It makes the code Async
Q adds the functions in the chain to the Event loop
When the promised function returns, the promises
are rejected/resolved during the next pass of the
runloop
Sunday, 25 August 13
Thank you
Code snippets used for the demo can be downloaded from
https://gist.github.com/senthilkumarv/6326192
Contact at senthilkumar@thoughtworks.com and kuldeepg@thoughtworks.com
Sunday, 25 August 13

More Related Content

PPT
jimmy hacking (at) Microsoft
PDF
GroovyConsole2
PDF
The Ring programming language version 1.7 book - Part 9 of 196
PDF
Async JavaScript in ES7
PPT
Evolution of asynchrony in (ASP).NET
PDF
Connecting NSClient++ to Icinga, Elasticsearch and Graphite - Icinga Camp Sto...
PPTX
Log4jprop example
PDF
The Ring programming language version 1.6 book - Part 8 of 189
jimmy hacking (at) Microsoft
GroovyConsole2
The Ring programming language version 1.7 book - Part 9 of 196
Async JavaScript in ES7
Evolution of asynchrony in (ASP).NET
Connecting NSClient++ to Icinga, Elasticsearch and Graphite - Icinga Camp Sto...
Log4jprop example
The Ring programming language version 1.6 book - Part 8 of 189

What's hot (20)

PDF
Kotlin workshop
PDF
MongoDB World 2016: Implementing Async Networking in MongoDB 3.2
PDF
OTcl and C++ linkages in NS2
PPTX
Kotlin Coroutines and Rx
PDF
Promises in JavaScript
PDF
Golang preso
PDF
The Ring programming language version 1.8 book - Part 88 of 202
PDF
Why is a[1] fast than a.get(1)
PDF
CycQL: A SPARQL Adapter for OpenCyc
PDF
«Продакшн в Kotlin DSL» Сергей Рыбалкин
PPT
Multithreading in PHP
PDF
Introduction to RxJS
PPTX
Sync with async
ODP
Debugging and Profiling Rails Application
PPTX
Cryptocurrency && Ruby
KEY
TDD Boot Camp 東京 for C++ 進行
RTF
R snippet
ODP
Django debugging
PDF
Java ME API Next
PDF
Groovy AST Demystified
Kotlin workshop
MongoDB World 2016: Implementing Async Networking in MongoDB 3.2
OTcl and C++ linkages in NS2
Kotlin Coroutines and Rx
Promises in JavaScript
Golang preso
The Ring programming language version 1.8 book - Part 88 of 202
Why is a[1] fast than a.get(1)
CycQL: A SPARQL Adapter for OpenCyc
«Продакшн в Kotlin DSL» Сергей Рыбалкин
Multithreading in PHP
Introduction to RxJS
Sync with async
Debugging and Profiling Rails Application
Cryptocurrency && Ruby
TDD Boot Camp 東京 for C++ 進行
R snippet
Django debugging
Java ME API Next
Groovy AST Demystified
Ad

Viewers also liked (12)

PDF
OpenCCC - WaterHackathon Delhi
PPT
Wow! closure in_javascript
PDF
JavaScript closures
PPT
Ambient Media Worldwide Ltd Jd Lr
PPTX
JavaScript closures
PDF
Callback Function
PPTX
javascript function & closure
PPTX
Closure
PDF
Callbacks, promises, generators - asynchronous javascript
PPTX
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
PPTX
JavaScript tips - Unnest callbacks and method declarations
PDF
The Top Skills That Can Get You Hired in 2017
OpenCCC - WaterHackathon Delhi
Wow! closure in_javascript
JavaScript closures
Ambient Media Worldwide Ltd Jd Lr
JavaScript closures
Callback Function
javascript function & closure
Closure
Callbacks, promises, generators - asynchronous javascript
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
JavaScript tips - Unnest callbacks and method declarations
The Top Skills That Can Get You Hired in 2017
Ad

Similar to Asynchronous JavaScript and Promises (20)

PDF
Introduction to Node JS2.pdf
PPTX
Async discussion 9_29_15
PDF
Javascript Promises/Q Library
PPTX
Java Script Promise
PDF
Asynchronous JavaScript Programming with Callbacks & Promises
PPTX
Avoiding callback hell in Node js using promises
PDF
Async js - Nemetschek Presentaion @ HackBulgaria
PDF
Javascript Promises
PDF
Getting Comfortable with JS Promises
PDF
Promises - Asynchronous Control Flow
PDF
Asynchronous development in JavaScript
PDF
Avoiding callback hell with promises
PDF
Practical JavaScript Promises
PDF
Javascript internals
PDF
Tech friday 22.01.2016
PDF
Kamil witecki asynchronous, yet readable, code
PDF
Intro to Asynchronous Javascript
PDF
JavaScript Promises Simplified [Free Meetup]
PPTX
JavaScript Promises
PDF
Promises, Promises: Mastering Async I/O in Javascript with the Promise Pattern
Introduction to Node JS2.pdf
Async discussion 9_29_15
Javascript Promises/Q Library
Java Script Promise
Asynchronous JavaScript Programming with Callbacks & Promises
Avoiding callback hell in Node js using promises
Async js - Nemetschek Presentaion @ HackBulgaria
Javascript Promises
Getting Comfortable with JS Promises
Promises - Asynchronous Control Flow
Asynchronous development in JavaScript
Avoiding callback hell with promises
Practical JavaScript Promises
Javascript internals
Tech friday 22.01.2016
Kamil witecki asynchronous, yet readable, code
Intro to Asynchronous Javascript
JavaScript Promises Simplified [Free Meetup]
JavaScript Promises
Promises, Promises: Mastering Async I/O in Javascript with the Promise Pattern

Recently uploaded (20)

PDF
Empathic Computing: Creating Shared Understanding
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Tartificialntelligence_presentation.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Electronic commerce courselecture one. Pdf
PPTX
1. Introduction to Computer Programming.pptx
PDF
Getting Started with Data Integration: FME Form 101
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Machine Learning_overview_presentation.pptx
PPTX
Big Data Technologies - Introduction.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Empathic Computing: Creating Shared Understanding
Accuracy of neural networks in brain wave diagnosis of schizophrenia
A comparative analysis of optical character recognition models for extracting...
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Machine learning based COVID-19 study performance prediction
Tartificialntelligence_presentation.pptx
Network Security Unit 5.pdf for BCA BBA.
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Mobile App Security Testing_ A Comprehensive Guide.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Electronic commerce courselecture one. Pdf
1. Introduction to Computer Programming.pptx
Getting Started with Data Integration: FME Form 101
Per capita expenditure prediction using model stacking based on satellite ima...
MYSQL Presentation for SQL database connectivity
Machine Learning_overview_presentation.pptx
Big Data Technologies - Introduction.pptx
MIND Revenue Release Quarter 2 2025 Press Release
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf

Asynchronous JavaScript and Promises

  • 2. Callbacks console.log("Before  readFile"); fs.readFile("file1.txt",  function(file1Content)  {    console.log("File  Contents  here");    return  "#"  +  file1Content  +  "#"; }); console.log("After  readFile"); Functions are first class citizens in JavaScript Functions can takes functions as argument and call them when they are done Sunday, 25 August 13
  • 3. Callbacks console.log("Before  readFile"); fs.readFile("file1.txt",  function(file1Content)  {    console.log("File  Contents  here");    return  "#"  +  file1Content  +  "#"; }); console.log("After  readFile"); Functions are first class citizens in JavaScript Functions can takes functions as argument and call them when they are done Sunday, 25 August 13
  • 4. Is JavaScript really Async? All of the JavaScript engines including V8 are single-threaded But all I/O is evented and asynchronous It is possible via the EventLoop Sunday, 25 August 13
  • 5. An entity that handles and processes external events and converts them into callback invocations Every asynchronous operation adds itself to the EventLoop Event Loops Sunday, 25 August 13
  • 9. Promises A Promise is an object that represents a one-time event, typically the outcome of an async task like an AJAX call. At first, a Promise is in a pending state. Eventually, it’s either resolved or rejected. Once a Promise is resolved or rejected, it’ll remain in that state forever, and its callbacks will never fire again. Sunday, 25 August 13
  • 11. Callback Hell step1(function  (value1)  {    step2(value1,  function(value2)  {        step3(value2,  function(value3)  {            step4(value3,  function(value4)  {                //  Do  something  with  value4            });        });    }); }); Q.fcall(promisedStep1) .then(promisedStep2) .then(promisedStep3) .then(promisedStep4) .then(function  (value4)  {        //  Do  something  with  value4 }) .done(); Promises can solve the problem of “Callback Hell” Sunday, 25 August 13
  • 12. Handling exceptions Promises also helps you handle exceptions in a cleaner way var  handleError  =  console.log; step1(function  (value1)  {    step2(value1,  function(value2)  {        step3(value2,  function(value3)  {            step4(value3,  function(value4)  {                //  Do  something  with  value4            },  handleError);        },  handleError);    },  handleError); },  handleError); Q.fcall(promisedStep1) .then(promisedStep2) .then(promisedStep3) .then(promisedStep4) .then(function(value4)  {        //  Do  something  with  value4 }) .fail(function(error)  {        //  Handle  any  error  from  all  above   steps }) .done(); Sunday, 25 August 13
  • 13. It makes the code Async Q adds the functions in the chain to the Event loop When the promised function returns, the promises are rejected/resolved during the next pass of the runloop Sunday, 25 August 13
  • 14. Thank you Code snippets used for the demo can be downloaded from https://gist.github.com/senthilkumarv/6326192 Contact at [email protected] and [email protected] Sunday, 25 August 13