Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Actually Understanding Asynchronous JavaScript
Search
Steve Kinney
August 04, 2016
Technology
220
1
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Actually Understanding Asynchronous JavaScript
Steve Kinney
August 04, 2016
More Decks by Steve Kinney
See All by Steve Kinney
Enterprise UI, v2
stevekinney
0
130
React_Performance__2022.pdf
stevekinney
0
36
React Performance v2
stevekinney
0
59
Introduction to Testing
stevekinney
0
180
Web Security, Frontend Masters
stevekinney
0
4.1k
Making Music with the Web Audio API, JSConf Colombia 2023
stevekinney
0
130
React and TypeScript, Turing School
stevekinney
0
380
Redux Workshop, 2021-05-05
stevekinney
2
2.2k
TypeScript and React Utility Types
stevekinney
1
230
Other Decks in Technology
See All in Technology
新しい SLO が良い感じにハマっている話
z63d
4
2.1k
Master Dataグループ紹介資料
sansan33
PRO
1
4.8k
AIがAPIを書く時代に、私たちは何を設計すべきか
nagix
0
210
攻撃と防御で学ぶAI時代のプロダクトセキュリティ演習
recruitengineers
PRO
1
380
侵入は突然に 〜 IoTマルウェアと悪用される家庭の機器 ~ / When Intrusion Strikes: IoT Malware and the Abuse of Home Devices
nttcom
0
1.5k
TypeScript入門 2026
recruitengineers
PRO
1
300
20260801_スクフェス大阪
kgnkhkr
1
1.1k
LangfuseによるLLMOps基盤の構築と活用事例
zozotech
PRO
1
280
【5分でわかる】セーフィー エンジニア向け会社紹介
safie_recruit
0
53k
認知負荷をGemini で溶かす — GKE 基盤「Orbit」における AI エージェントの実践
sansantech
PRO
1
250
Issue設計から始める仕様駆動開発 / 20260731 Mizuki Hirata
shift_evolve
PRO
1
130
toio・myCobotでフィジカルAIっぽいことを行うための検討(とりあえず調査) / フィジカルAI LT(IoTLTによる開催)
you
PRO
0
280
Featured
See All Featured
GraphQLの誤解/rethinking-graphql
sonatard
75
12k
How to make the Groovebox
asonas
2
2.3k
The innovator’s Mindset - Leading Through an Era of Exponential Change - McGill University 2025
jdejongh
PRO
1
230
Accessibility Awareness
sabderemane
1
170
Efficient Content Optimization with Google Search Console & Apps Script
katarinadahlin
PRO
1
760
Why Mistakes Are the Best Teachers: Turning Failure into a Pathway for Growth
auna
0
190
Bootstrapping a Software Product
garrettdimon
PRO
307
120k
Impact Scores and Hybrid Strategies: The future of link building
tamaranovitovic
0
360
Bioeconomy Workshop: Dr. Julius Ecuru, Opportunities for a Bioeconomy in West Africa
akademiya2063
PRO
1
190
Designing Experiences People Love
moore
143
24k
DevOps and Value Stream Thinking: Enabling flow, efficiency and business value
helenjbeal
1
290
Documentation Writing (for coders)
carmenintech
77
5.4k
Transcript
Actually Understanding Asynchronous JavaScript
I'm Steve. @stevekinney
I'm Steve. @stevekinney
http://turing.io
http://bit.ly/electronjs
None
PSA: Stop me ay any point to ask any and
all questions.
What does "asynchronous" even mean?
To find out, let's torture some metaphors!
None
Running Errands Synchronously
None
None
None
None
None
None
None
Running Errands Asynchronously
None
None
None
None
None
Functions Run to Completion
None
None
None
None
None
None
None
None
None
None
None
What constitutes "completion?" • Hitting the end of a function
• Reaching a return statement • Throwing an error (and not catching it)
None
What Happens When the Browser Blocks?
What Happens When the Browser Blocks?
None
Asynchronous JavaScript is based on events.
document.addEventListener('click', function () { alert('Congratulations, you clicked on the web
page.'); });
None
The Call Stack A data structure that keeps track of
where we are in the execution of our programs.
var possessions = []; var lifeSavings = 25; function goGroceryShopping()
{ buyVeganHam(); } function buyVeganHam() { if (lifeSavings < 10) { throw new Error('Not enough money.'); } lifeSavings = lifeSavings - 10; possessions.push('vegan ham'); } goGroceryShopping();
Call Stack
Top Level Call Stack
Top Level goGroceryShopping Call Stack
Top Level goGroceryShopping buyVeganHam Call Stack
Top Level goGroceryShopping Call Stack
Top Level Call Stack
Call Stack
var possessions = []; var lifeSavings = 25; function goGroceryShopping()
{ buyOrganicAlmondMilk(); buyVeganHam(); } function buyOrganicAlmondMilk() { lifeSavings = lifeSavings - 20; possessions.push('organic almond milk'); } function buyVeganHam() { // When this code eventually executes, we'll only have $5 left. if (lifeSavings < 10) { throw new Error('Not enough money.'); } lifeSavings = lifeSavings - 10; possessions.push('vegan ham'); } goGroceryShopping();
You've seen the Call Stack before.
Call Stack
Top Level Call Stack
Top Level goGroceryShopping Call Stack
Top Level goGroceryShopping buyOrganicAlmondMilk Call Stack
Top Level goGroceryShopping Call Stack
Top Level goGroceryShopping Call Stack buyVeganHam
Top Level goGroceryShopping Call Stack
Top Level Call Stack
Call Stack
None
The Event Queue A list of functions that are handled
in a first-in, first-out order.
The Event Loop A programming construct that waits for and
dispatches functions in the Event Queue to the Call Stack.
Queue
Queue A very important click event Some mildly important AJAX
response A frivolous click event
Queue Some mildly important AJAX response A frivolous click event
Queue A frivolous click event
Queue
Queue Call Stack
Queue Call Stack Some mildly important AJAX response
Queue Call Stack Some mildly important AJAX response
Queue A very important click event Call Stack
Queue A very important click event A frivolous click event
Call Stack
Queue A very important click event A frivolous click event
Call Stack
Queue A frivolous click event Call Stack
Queue A frivolous click event Call Stack
Queue Call Stack
Turns out that JavaScript isn't asynchronous after all.
It's the environment.
None
None
None
setTimeout(function () { console.log('I will happen later.'); }, 5000); Timers
setTimeout is available in all browsers and Node.js
Timers will be added to the Event Queue after that
number of milliseconds.
Queue Top Level goGroceryShopping buyVeganHams Call Stack
Queue Top Level goGroceryShopping buyVeganHams Call Stack setTimeout(…, 1000)
Queue Top Level goGroceryShopping buyVeganHams Call Stack setTimeout(…, 1000)
Queue Top Level goGroceryShopping buyVeganHams Call Stack thisWillBlockUpTheWorksAndNeverComplete setTimeout(…, 1000)
Queue Top Level goGroceryShopping buyVeganHams Call Stack thisWillBlockUpTheWorksAndNeverComplete setTimeout(…, 1000)
The Callback Pattern
Callbacks aren't anything special.
Functions can be passed as arguments to functions.
function callbackSandwich(callbackFunction) { console.log('Top piece of bread.'); callbackFunction(); console.log('Bottom piece
of bread.'); } callbackSandwich(function () {console.log('American cheese.')});
Sometimes we'll guard against blowing things up if a callback
function isn't provided.
function callbackSandwich(callbackFunction) { console.log('Top piece of bread.'); if (typeof callbackFunction
=== 'function') callbackFunction(); console.log('Bottom piece of bread.'); } callbackSandwich(function () {console.log('American cheese.')}); callbackSandwich(); // Just two pieces of bread.
From Events Listeners to Callbacks
None
None
None
None
None
None
None
None
None
None
None
None
None
So now…
None
None
Promises
Callbacks have some problems.
We can usually only do one thing with the data
from the event.
We can't store the result anywhere.
None
None
None
"Inversion of Control"
None
Libraries: Q, Bluebird, RSVP
None
.then()
Promise Chaining
asyncMultiply(2, 3).then(c => c * 1000).then(c => console.log(c)); Promise Chaining
The return value of the previous link is passed to the next then() method.
None
None
asyncMultiply(2, 3).then(c => c * 1000) .then(c => { throw
new Error('KABOOM!') }) .catch(e => console.error(e));
asyncMultiply(2, 3).then(c => c * 1000) .then(c => { throw
new Error('KABOOM!') })
None
None
None
None
None
None
None
Refactoring Our Callback Pattern
None
None
None
None
None
None
None
Promise.all() http://bit.ly/async- lab-promise-all
Promise.race()
http://turing.io http://bit.ly/electronjs