SlideShare a Scribd company logo
Async ... Await
Concurrency In JavaScript
Athman Gude
Concurrency
Doing multiple tasks over a period of time
(Generally order-independent or partially ordered units of work)
Concurrency is important when
waiting on input/ output such as
network requests, reading/
reading from disk or user input
Typically, programs wait for IO in two ways:
- Blocking (Synchronous)
- Easy to write
- Uses multithreading
- Memory and context-switching overhead
- Non-blocking / event-loop (Asynchronous)
- Single-threaded
- High-concurrency with low memory consumption
- Great for UI and IO-bound services rather than CPU bound
All modern JavaScript engines
use the non-blocking/ event
loop approach
So what happens if you block in JavaScript?
There are a few things that will block
- alert/ prompt/ confirm
- Synchronous XMLHttpRequest
- fs.readFileSync and file operation in Node
Blocking in the browser will halt
everything, including all user
interaction, even scrolling
Callbacks
Just pass a function that will be
called when the task is complete
Callbacks
Callbacks
The good and the bad
The Promise Land
Thin but powerful abstraction on top of callbacks.
Solves several problems:
- Easy chaining for sequential and parallel tasks
- Error handling
- Composable; can pass around a representation
It’s better, I promise
In its basic form, it looks no better than callback style
… but you actually get a lot more
But we are still putting callbacks inside .then()
Can we do better?
But JavaScript is still single-threaded
So we can’t block
However …
There is a special thing called a “Generator
Function” that can be paused
Promises + Generators
=
Awesome!
async … await
It’s a win
We get back most of our traditional constructs
- for/ while
- try/ catch
- Readable, sequential program flow
- Powerful inter-op with promises
It’s just promises
- An async function always returns a promise
- When we await a promise, our function pauses until the
promise is resolved
- We can still use all our favorite promise helpers such as
Promise.all()
Pro Tips
- Don’t forget to await
- Be careful about doing too much sequentially when
you can actually do it in parallel
- Using await in map/filter won’t do what you might
expect!
- Even though it looks synchronous, your code has
been paused and resumed
(function() { console.log(thank y’all) })()

More Related Content

What's hot

Spring Core
Spring CoreSpring Core
Spring Core
Pushan Bhattacharya
 
Uploading a file with php
Uploading a file with phpUploading a file with php
Uploading a file with php
Muhamad Al Imran
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
Sunil OS
 
Les dessous du framework spring
Les dessous du framework springLes dessous du framework spring
Les dessous du framework spring
Antoine Rey
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
Forziatech
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
Jeevesh Pandey
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFuture
José Paumard
 
React hooks
React hooksReact hooks
React hooks
Ramy ElBasyouni
 
Rest API
Rest APIRest API
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
Ankit Agarwal
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
Maulik Shah
 
PHP slides
PHP slidesPHP slides
PHP slides
Farzad Wadia
 
Understanding REST
Understanding RESTUnderstanding REST
Understanding REST
Nitin Pande
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
Garrett Welson
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVC
IndicThreads
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
Fahmi Jafar
 
Servlets
ServletsServlets
Servlets
Geethu Mohan
 
React js use contexts and useContext hook
React js use contexts and useContext hookReact js use contexts and useContext hook
React js use contexts and useContext hook
Piyush Jamwal
 
Object Oriented Javascript
Object Oriented JavascriptObject Oriented Javascript
Object Oriented Javascript
NexThoughts Technologies
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Edureka!
 

What's hot (20)

Spring Core
Spring CoreSpring Core
Spring Core
 
Uploading a file with php
Uploading a file with phpUploading a file with php
Uploading a file with php
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Les dessous du framework spring
Les dessous du framework springLes dessous du framework spring
Les dessous du framework spring
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFuture
 
React hooks
React hooksReact hooks
React hooks
 
Rest API
Rest APIRest API
Rest API
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
PHP slides
PHP slidesPHP slides
PHP slides
 
Understanding REST
Understanding RESTUnderstanding REST
Understanding REST
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVC
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
 
Servlets
ServletsServlets
Servlets
 
React js use contexts and useContext hook
React js use contexts and useContext hookReact js use contexts and useContext hook
React js use contexts and useContext hook
 
Object Oriented Javascript
Object Oriented JavascriptObject Oriented Javascript
Object Oriented Javascript
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
 

Similar to Async ... Await – concurrency in java script

Os Smarr
Os SmarrOs Smarr
Os Smarr
oscon2007
 
Smarr Oscon 2007
Smarr Oscon 2007Smarr Oscon 2007
Smarr Oscon 2007
briandemant
 
Asynchronous programming - .NET Way
Asynchronous programming - .NET WayAsynchronous programming - .NET Way
Asynchronous programming - .NET Way
Bishnu Rawal
 
The art of concurrent programming
The art of concurrent programmingThe art of concurrent programming
The art of concurrent programming
Iskren Chernev
 
Asynchronous Programming in .NET
Asynchronous Programming in .NETAsynchronous Programming in .NET
Asynchronous Programming in .NET
Pierre-Luc Maheu
 
Async.pdf
Async.pdfAsync.pdf
Synchronous vs Asynchronous Programming
Synchronous vs Asynchronous ProgrammingSynchronous vs Asynchronous Programming
Synchronous vs Asynchronous Programming
jeetendra mandal
 
PyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous ProgrammingPyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous Programming
Juti Noppornpitak
 
Asynchronyin net
Asynchronyin netAsynchronyin net
Asynchronyin net
Soacat Blogspot
 
Rust's Journey to Async/await
Rust's Journey to Async/awaitRust's Journey to Async/await
Rust's Journey to Async/await
C4Media
 
High performance java script why everything youve been taught is wrong
High performance java script why everything youve been taught is wrongHigh performance java script why everything youve been taught is wrong
High performance java script why everything youve been taught is wrong
Tao Gao
 
os ass.pptx
os ass.pptxos ass.pptx
os ass.pptx
kavinaya9
 
A first look into the Project Loom in Java
A first look into the Project Loom in JavaA first look into the Project Loom in Java
A first look into the Project Loom in Java
Lukas Steinbrecher
 
Async Await for Mobile Apps
Async Await for Mobile AppsAsync Await for Mobile Apps
Async Await for Mobile Apps
Craig Dunn
 
Go performance tooling
Go performance toolingGo performance tooling
Go performance tooling
Adil Hafeez
 
MNPHP Scalable Architecture 101 - Feb 3 2011
MNPHP Scalable Architecture 101 - Feb 3 2011MNPHP Scalable Architecture 101 - Feb 3 2011
MNPHP Scalable Architecture 101 - Feb 3 2011
Mike Willbanks
 
Life in the Fast Lane: Full Speed XPages!, #dd13
Life in the Fast Lane: Full Speed XPages!, #dd13Life in the Fast Lane: Full Speed XPages!, #dd13
Life in the Fast Lane: Full Speed XPages!, #dd13
Dominopoint - Italian Lotus User Group
 
5 - ch3.pptx
5 - ch3.pptx5 - ch3.pptx
5 - ch3.pptx
Temp35704
 
Web assembly with PWA
Web assembly with PWA Web assembly with PWA
Web assembly with PWA
Shashank Sharma
 
web, spa vs traditional - 2016
web, spa vs traditional - 2016web, spa vs traditional - 2016
web, spa vs traditional - 2016
Yauheni Nikanovich
 

Similar to Async ... Await – concurrency in java script (20)

Os Smarr
Os SmarrOs Smarr
Os Smarr
 
Smarr Oscon 2007
Smarr Oscon 2007Smarr Oscon 2007
Smarr Oscon 2007
 
Asynchronous programming - .NET Way
Asynchronous programming - .NET WayAsynchronous programming - .NET Way
Asynchronous programming - .NET Way
 
The art of concurrent programming
The art of concurrent programmingThe art of concurrent programming
The art of concurrent programming
 
Asynchronous Programming in .NET
Asynchronous Programming in .NETAsynchronous Programming in .NET
Asynchronous Programming in .NET
 
Async.pdf
Async.pdfAsync.pdf
Async.pdf
 
Synchronous vs Asynchronous Programming
Synchronous vs Asynchronous ProgrammingSynchronous vs Asynchronous Programming
Synchronous vs Asynchronous Programming
 
PyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous ProgrammingPyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous Programming
 
Asynchronyin net
Asynchronyin netAsynchronyin net
Asynchronyin net
 
Rust's Journey to Async/await
Rust's Journey to Async/awaitRust's Journey to Async/await
Rust's Journey to Async/await
 
High performance java script why everything youve been taught is wrong
High performance java script why everything youve been taught is wrongHigh performance java script why everything youve been taught is wrong
High performance java script why everything youve been taught is wrong
 
os ass.pptx
os ass.pptxos ass.pptx
os ass.pptx
 
A first look into the Project Loom in Java
A first look into the Project Loom in JavaA first look into the Project Loom in Java
A first look into the Project Loom in Java
 
Async Await for Mobile Apps
Async Await for Mobile AppsAsync Await for Mobile Apps
Async Await for Mobile Apps
 
Go performance tooling
Go performance toolingGo performance tooling
Go performance tooling
 
MNPHP Scalable Architecture 101 - Feb 3 2011
MNPHP Scalable Architecture 101 - Feb 3 2011MNPHP Scalable Architecture 101 - Feb 3 2011
MNPHP Scalable Architecture 101 - Feb 3 2011
 
Life in the Fast Lane: Full Speed XPages!, #dd13
Life in the Fast Lane: Full Speed XPages!, #dd13Life in the Fast Lane: Full Speed XPages!, #dd13
Life in the Fast Lane: Full Speed XPages!, #dd13
 
5 - ch3.pptx
5 - ch3.pptx5 - ch3.pptx
5 - ch3.pptx
 
Web assembly with PWA
Web assembly with PWA Web assembly with PWA
Web assembly with PWA
 
web, spa vs traditional - 2016
web, spa vs traditional - 2016web, spa vs traditional - 2016
web, spa vs traditional - 2016
 

Recently uploaded

Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
Remote DBA Services
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
Peter Muessig
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
dakas1
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
sjcobrien
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
What next after learning python programming basics
What next after learning python programming basicsWhat next after learning python programming basics
What next after learning python programming basics
Rakesh Kumar R
 
Mobile app Development Services | Drona Infotech
Mobile app Development Services  | Drona InfotechMobile app Development Services  | Drona Infotech
Mobile app Development Services | Drona Infotech
Drona Infotech
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
Peter Muessig
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
TaghreedAltamimi
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
XfilesPro
 
316895207-SAP-Oil-and-Gas-Downstream-Training.pptx
316895207-SAP-Oil-and-Gas-Downstream-Training.pptx316895207-SAP-Oil-and-Gas-Downstream-Training.pptx
316895207-SAP-Oil-and-Gas-Downstream-Training.pptx
ssuserad3af4
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
SOCRadar
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
Peter Muessig
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 

Recently uploaded (20)

Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
What next after learning python programming basics
What next after learning python programming basicsWhat next after learning python programming basics
What next after learning python programming basics
 
Mobile app Development Services | Drona Infotech
Mobile app Development Services  | Drona InfotechMobile app Development Services  | Drona Infotech
Mobile app Development Services | Drona Infotech
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
 
316895207-SAP-Oil-and-Gas-Downstream-Training.pptx
316895207-SAP-Oil-and-Gas-Downstream-Training.pptx316895207-SAP-Oil-and-Gas-Downstream-Training.pptx
316895207-SAP-Oil-and-Gas-Downstream-Training.pptx
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 

Async ... Await – concurrency in java script

  • 1. Async ... Await Concurrency In JavaScript Athman Gude
  • 2. Concurrency Doing multiple tasks over a period of time (Generally order-independent or partially ordered units of work)
  • 3.
  • 4. Concurrency is important when waiting on input/ output such as network requests, reading/ reading from disk or user input
  • 5. Typically, programs wait for IO in two ways: - Blocking (Synchronous) - Easy to write - Uses multithreading - Memory and context-switching overhead - Non-blocking / event-loop (Asynchronous) - Single-threaded - High-concurrency with low memory consumption - Great for UI and IO-bound services rather than CPU bound
  • 6. All modern JavaScript engines use the non-blocking/ event loop approach
  • 7. So what happens if you block in JavaScript? There are a few things that will block - alert/ prompt/ confirm - Synchronous XMLHttpRequest - fs.readFileSync and file operation in Node
  • 8. Blocking in the browser will halt everything, including all user interaction, even scrolling
  • 9. Callbacks Just pass a function that will be called when the task is complete
  • 12.
  • 13.
  • 14.
  • 15. The Promise Land Thin but powerful abstraction on top of callbacks. Solves several problems: - Easy chaining for sequential and parallel tasks - Error handling - Composable; can pass around a representation
  • 16.
  • 17. It’s better, I promise In its basic form, it looks no better than callback style … but you actually get a lot more
  • 18.
  • 19.
  • 20.
  • 21. But we are still putting callbacks inside .then() Can we do better?
  • 22.
  • 23. But JavaScript is still single-threaded So we can’t block
  • 24. However … There is a special thing called a “Generator Function” that can be paused
  • 25.
  • 26.
  • 29.
  • 30. It’s a win We get back most of our traditional constructs - for/ while - try/ catch - Readable, sequential program flow - Powerful inter-op with promises
  • 31.
  • 32.
  • 33. It’s just promises - An async function always returns a promise - When we await a promise, our function pauses until the promise is resolved - We can still use all our favorite promise helpers such as Promise.all()
  • 34.
  • 35. Pro Tips - Don’t forget to await - Be careful about doing too much sequentially when you can actually do it in parallel - Using await in map/filter won’t do what you might expect! - Even though it looks synchronous, your code has been paused and resumed
  • 36.

Editor's Notes

  1. Today we’ll talk about concurrency in modern JavaScript Introduce myself My name is Athman Gude I am JavaScript and React Engineer
  2. Typically one core can only do one thing at any moment But over a period of time we want to do a number of things. For instance an API server wants to serve multiple requests from clients, a script wants to read multiple values from a database before it returns a response. What we are talking about is doing multiple things over a period of time and some of those things we can do in parallel and some we have to do one at a time sequentially Generally, order-dependent or partially ordered units of work is where concurrency happens.
  3. This is an example of concurrency In this example we see a number of different tasks that start at different times but are kind of running over the same duration of time in parallel This is something that is kinda hard to do in computing, in particular it’s hard to reason about, it leads to race conditions, it leads to different models of things changing over time
  4. Concurrency is particularly important when waiting on IO such as network requests, reading from or writing to sisk, user input etc. Actually anything that is considered an asynchronous kind of activity where the CPU need to wait for the user do something or where the it needs to wait for data to arrive from the user or the network
  5. Typically programs wait for IO in two ways Synchronous IO Synchronous IO is easy to write It’s what we see in languages like Ruby or PHP, Python and that’s what most web server-side technologies are doing In order for that that to work we need multithreading because if we stop one thread we need another thread to be able to continue working But it’s easy to write because you write everything sequentially However there is a memory overhead to that because every thread requires memory and also there is also context switching when the CPU switches between the threads In Asynchronous IO So Asynchronous IO is the other way to handle IO And that is the event loop style that is single threaded so everything runs on one thread meaning we cannot block the thread However we get high concurrency and also it uses less memory It’s really good for UI, User interaction stuff that’s where the browser uses the event loop And also good for IO bound services. Things that are reading a lot from networks or databases or disks But not so great on CPU bound work because anything that is using the CPU is going to prevent other things from happening So that’s a bit of the overview of the two patterns And JavaScript as you know it is ……………….. The later one. Yeah everything runs on one thread
  6. Actually most browsers and server side JavaScript engines like V8, Chakra and frameworks are event driven or non-blocking There are some exceptions to that Like historically some browsers like NetScape are said to have been multi-threaded
  7. So what happens if you block in JavaScript There are some things that will block the execution We have alert and family Synchronous style of XMLHttpRequest, I remember working with this way back before I learnt about jQuery. It was probably a mistake or at least it was a bad idea. It shouldn’t really be that way But this is rare and people don’t use it anymore We also have some stuff in Node world that are intentionally synchronous for various reasons
  8. I think the one that everyone is familiar with is the alert style that blocks everything that is happening The page puts a dialog up and everything pauses. You can’t interact with the page, can’t press a button. You can’t even scroll And that’s kind of a bad bad user experience
  9. So how do we write concurrent software without blocking Generally in Javascript we use callbacks and it’s pretty straight forward. We just pass a function and when a task is finished JavaScript will call our function. For instance on an onclick event, A network request When reading files so the file is read and when it’s done our function is called
  10. Here we are gonna read a file and when we are done we have our content Does anyone understand the callback style Basically every JavaScript code you have written
  11. So what are the pros and cons of callbacks? Pros With callbacks we get a pretty good low level abstraction for concurrency for Asynchronous actions They performant with low overhead since there is no context switching involved You can do almost any Asynchronous tasks with callbacks So What’s the downside Cons Doing things in sequence is hard. But doing things in parallel is even harder You give up constructs you are familiar with such as for/ while and try…catch and these are things that people come from a Python or PHP background for and almost any other language and they don’t understand how you cannot do these things Error handling is no so great. Well you have to check for this error parameter as things could always fail in the middle of a network request etc. Code readability goes downhill and applications become hard to maintain, we get callback hell It’s also challenging to test
  12. “What’s wrong with my code?” You see this stuff on Stack overflow every day Can anybody help this poor PHP programmer to debug this?
  13. Here we are taking three files and we want to find the total number of bytes for these three files callbacks they add complexity it's messy to chain them And we haven’t done any error checking here
  14. Same as before but done in parallel How do we know we are done because the answer might come back in any order
  15. We have talked about Callbacks and now let’s talk about promises They are basically an abstraction of a callback and gives us the chaining that we need when doing tasks sequentially i,e task1 then wait till it finishes then task2 … It gives us the helpers to do things in parallel and And gives us error handling And they are composable And the way a promise works is we can pass around a representation of a future value So a promise is an object that represents what the value will be when the operation finishes
  16. Here is how we would read a file using promises We see that we get a “then” and a “catch” which are super handy
  17. It’s better because we can do some chaining on that Error handling I know it doesn’t look that sexy but it’s better. I know
  18. Here is an example of chaining promises. More like setTimout() in Promise Land This might be a little bit more than callbacks but it’s not that amazing
  19. This is an example that gives us flow control with promises We are doing some thnigs in sequence while others can be done in parallel
  20. Error handling Just one catch at the very end catches them all
  21. We are still doing callbacks even though putting them inside then But we are still having to provide the functions Can we just have a normal sequential program like in other languages?
  22. Here is what we want Declare a promise, wait for it to resolve and get the result That would be lovely
  23. We can’t stop the program in the previous slide just like when we have alert then the whole application will freeze until the pronise is resolved
  24. Here’s where things start getting exciting. So we can pause just one function and not the entire program and be able to resume it later
  25. Here’s how it looks like Take note of the star and the yield Generators are not about Asynchronous or event loop but just about pausing stuff There needs to be something controlling the resuming Some function needs to resume this whenever the fetch has completed Generators are pretty complex But they are the only thing that allows this to work So what happens when we combine Promises with Generators?
  26. More examples on generators representing the whole set of integers Here the function count is not gonna do anything just by calling it until we request the first value Then it’s going to pause right there and until we request the next value
  27. This is what it’s been all about guys
  28. Finally we are here async … await Is basically a thin layer of syntax over Promises and Generators
  29. Here is how it looks like Instead of a function start we have this ASYNC function It’s really similar to the function star We use the keyword await before a promise and it always have to be that way Await will pause it in the middle of execution and let the event loop do other stuff and finally when the promise it resolved then the function is resumed This is the whole story about async … await
  30. Works with any promisified library
  31. The read file example Two things could go wrong here Read file could throw an exception in Async World but we will still catch it
  32. Here we take an html element and we want to move it to the right every frame
  33. Here’s where things start getting exciting. So we can pause just one function and not the entire program and be able to resume it later
  34. Fetch friends with promise.all We do the first two things sequentially But fetching friends is fetched in Parallel The function getUserFriends() returns a promise itself because it is async
  35. Probably the first program I wrote after Hello World in C