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
210
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
38
React_Performance__2022.pdf
stevekinney
0
31
React Performance v2
stevekinney
0
48
Introduction to Testing
stevekinney
0
170
Web Security, Frontend Masters
stevekinney
0
3.9k
Making Music with the Web Audio API, JSConf Colombia 2023
stevekinney
0
120
React and TypeScript, Turing School
stevekinney
0
380
Redux Workshop, 2021-05-05
stevekinney
2
2.2k
TypeScript and React Utility Types
stevekinney
1
220
Other Decks in Technology
See All in Technology
【2026年版】 ベクトル検索とEmbedding最前線
mocobeta
18
4.8k
2026TECHFRESH畢業分享會 - Lightning Talk - E起 See See : 電商推薦讀心術? 數據說了算
line_developers_tw
PRO
0
1.3k
Bucharest Tech Week 2026 - Reinventing testing practices in the AI era
edeandrea
PRO
1
170
PostgreSQL 19 新機能概要 OSC Hokkaido 2026
nori_shinoda
0
160
SteampipeとExcel Power QueryでAWS構成定義書の作成を自動化する
jhashimoto
0
160
自分が詳しくない領域でAIを使う #プロヒス2026
konifar
14
5.4k
iAEONの段階的リアーキテクト戦略 / iAEON's_Gradual_Re-architecture_Strategy
aeonpeople
0
230
Claude Codeをどのように キャッチアップしているか
oikon48
13
8.6k
攻撃者視点で考えるDetection Engineering
cryptopeg
3
2k
白金鉱業Meetup_Vol.24_「AIエージェントは分けるほど良い」は本当か? / Is it true that “the more you divide AI agents, the better”?
brainpadpr
1
420
AI-DLCを “そのまま導入しなかった”話 ~組織に合わせてアジャストした 私たちの実践共有~
hiroramos4
PRO
0
220
秘密度ラベル初心者が第1歩でつまづかないための「設計・運用」ポイント
seafay
PRO
0
240
Featured
See All Featured
Fight the Zombie Pattern Library - RWD Summit 2016
marcelosomers
234
17k
The Illustrated Guide to Node.js - THAT Conference 2024
reverentgeek
1
390
Cheating the UX When There Is Nothing More to Optimize - PixelPioneers
stephaniewalter
287
14k
Digital Projects Gone Horribly Wrong (And the UX Pros Who Still Save the Day) - Dean Schuster
uxyall
1
1.7k
How To Speak Unicorn (iThemes Webinar)
marktimemedia
1
490
HTML-Aware ERB: The Path to Reactive Rendering @ RubyCon 2026, Rimini, Italy
marcoroth
1
200
svc-hook: hooking system calls on ARM64 by binary rewriting
retrage
2
300
Bioeconomy Workshop: Dr. Julius Ecuru, Opportunities for a Bioeconomy in West Africa
akademiya2063
PRO
1
150
Building Better People: How to give real-time feedback that sticks.
wjessup
370
20k
Lightning talk: Run Django tests with GitHub Actions
sabderemane
0
200
How People are Using Generative and Agentic AI to Supercharge Their Products, Projects, Services and Value Streams Today
helenjbeal
1
220
StorybookのUI Testing Handbookを読んだ
zakiyama
31
6.8k
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