SlideShare uma empresa Scribd logo
1 de 14
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

MongoDB World 2016: Implementing Async Networking in MongoDB 3.2
MongoDB World 2016: Implementing Async Networking in MongoDB 3.2MongoDB World 2016: Implementing Async Networking in MongoDB 3.2
MongoDB World 2016: Implementing Async Networking in MongoDB 3.2MongoDB
 
OTcl and C++ linkages in NS2
OTcl and C++ linkages in NS2OTcl and C++ linkages in NS2
OTcl and C++ linkages in NS2Pradeep Kumar TS
 
Promises in JavaScript
Promises in JavaScriptPromises in JavaScript
Promises in JavaScriptRevath S Kumar
 
The Ring programming language version 1.8 book - Part 88 of 202
The Ring programming language version 1.8 book - Part 88 of 202The Ring programming language version 1.8 book - Part 88 of 202
The Ring programming language version 1.8 book - Part 88 of 202Mahmoud Samir Fayed
 
Why is a[1] fast than a.get(1)
Why is a[1]  fast than a.get(1)Why is a[1]  fast than a.get(1)
Why is a[1] fast than a.get(1)kao kuo-tung
 
CycQL: A SPARQL Adapter for OpenCyc
CycQL: A SPARQL Adapter for OpenCycCycQL: A SPARQL Adapter for OpenCyc
CycQL: A SPARQL Adapter for OpenCycSteven Battle
 
«Продакшн в Kotlin DSL» Сергей Рыбалкин
«Продакшн в Kotlin DSL» Сергей Рыбалкин«Продакшн в Kotlin DSL» Сергей Рыбалкин
«Продакшн в Kotlin DSL» Сергей РыбалкинMail.ru Group
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSBrainhub
 
Sync with async
Sync with  asyncSync with  async
Sync with asyncprabathsl
 
Debugging and Profiling Rails Application
Debugging and Profiling Rails ApplicationDebugging and Profiling Rails Application
Debugging and Profiling Rails ApplicationDavid Paluy
 
TDD Boot Camp 東京 for C++ 進行
TDD Boot Camp 東京 for C++ 進行TDD Boot Camp 東京 for C++ 進行
TDD Boot Camp 東京 for C++ 進行Takashi Imagire
 
Groovy AST Demystified
Groovy AST DemystifiedGroovy AST Demystified
Groovy AST DemystifiedAndres Almiray
 

Mais procurados (20)

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

Destaque

OpenCCC - WaterHackathon Delhi
OpenCCC - WaterHackathon DelhiOpenCCC - WaterHackathon Delhi
OpenCCC - WaterHackathon DelhiSenthil Kumar
 
Wow! closure in_javascript
Wow! closure in_javascriptWow! closure in_javascript
Wow! closure in_javascriptcnlangzi
 
Ambient Media Worldwide Ltd Jd Lr
Ambient Media Worldwide Ltd Jd LrAmbient Media Worldwide Ltd Jd Lr
Ambient Media Worldwide Ltd Jd LrJohnnboy75
 
JavaScript closures
JavaScript closuresJavaScript closures
JavaScript closuresHorky Chen
 
javascript function & closure
javascript function & closurejavascript function & closure
javascript function & closureHika Maeng
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptŁukasz Kużyński
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
JavaScript tips - Unnest callbacks and method declarations
JavaScript tips - Unnest callbacks and method declarationsJavaScript tips - Unnest callbacks and method declarations
JavaScript tips - Unnest callbacks and method declarationsexponential_io
 
The Top Skills That Can Get You Hired in 2017
The Top Skills That Can Get You Hired in 2017The Top Skills That Can Get You Hired in 2017
The Top Skills That Can Get You Hired in 2017LinkedIn
 

Destaque (12)

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

Semelhante a Asynchronous JavaScript and Promises

JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023Laurence Svekis ✔
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsBrian Moschel
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...julien.ponge
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming heroThe Software House
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsPiotr Pelczar
 
Functions - complex first class citizen
Functions - complex first class citizenFunctions - complex first class citizen
Functions - complex first class citizenVytautas Butkus
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsColin DeCarlo
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeCory Forsyth
 
Akka Futures and Akka Remoting
Akka Futures  and Akka RemotingAkka Futures  and Akka Remoting
Akka Futures and Akka RemotingKnoldus Inc.
 
Test-driven JavaScript Development - OPITZ CONSULTING - Tobias Bosch - Stefa...
Test-driven JavaScript Development - OPITZ CONSULTING -  Tobias Bosch - Stefa...Test-driven JavaScript Development - OPITZ CONSULTING -  Tobias Bosch - Stefa...
Test-driven JavaScript Development - OPITZ CONSULTING - Tobias Bosch - Stefa...OPITZ CONSULTING Deutschland
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}.toster
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch
 

Semelhante a Asynchronous JavaScript and Promises (20)

JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
Java scriptconfusingbits
Java scriptconfusingbitsJava scriptconfusingbits
Java scriptconfusingbits
 
Java scriptconfusingbits
Java scriptconfusingbitsJava scriptconfusingbits
Java scriptconfusingbits
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming hero
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Functions - complex first class citizen
Functions - complex first class citizenFunctions - complex first class citizen
Functions - complex first class citizen
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
 
Akka Futures and Akka Remoting
Akka Futures  and Akka RemotingAkka Futures  and Akka Remoting
Akka Futures and Akka Remoting
 
Test-driven JavaScript Development - OPITZ CONSULTING - Tobias Bosch - Stefa...
Test-driven JavaScript Development - OPITZ CONSULTING -  Tobias Bosch - Stefa...Test-driven JavaScript Development - OPITZ CONSULTING -  Tobias Bosch - Stefa...
Test-driven JavaScript Development - OPITZ CONSULTING - Tobias Bosch - Stefa...
 
Testing with Node.js
Testing with Node.jsTesting with Node.js
Testing with Node.js
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
NodeJS
NodeJSNodeJS
NodeJS
 
Deferred
DeferredDeferred
Deferred
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
 
oojs
oojsoojs
oojs
 

Último

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 

Último (20)

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 

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 senthilkumar@thoughtworks.com and kuldeepg@thoughtworks.com Sunday, 25 August 13