SlideShare a Scribd company logo
Intro to Asynchronous
Javascript
Garrett Welson
About me
• Graduate from Hack Reactor,
a software engineering
immersive program located at
Galvanize in downtown ATX
• Work at Hack Reactor as a
Resident, where I mentor
junior engineers, teach
concepts + best practices
• My first tech conference!
Goals
• Understand what asynchronous code is and why it
works differently from synchronous code
• The event loop
• Understand how to work with asynchronous code
• Callbacks 🙁 —> Promises 🙂 —> Async/Await 🤯
• Understand what’s happening under the hood with
these newer methods, and how to refactor old code
What is the event
loop?
Javascript 101
• Javascript is single-threaded
• Code is generally synchronous
• Javascript interprets each line right away
before moving on to what’s next
• Code is expected to be non-blocking
An early mistake…
let data = fetch('https://jsonplaceholder.typicode.com/posts')
console.log(data)
An early mistake…
let data = fetch('https://jsonplaceholder.typicode.com/posts')
console.log(data) // logs: Promise {<pending>}
Call Stack
const myName = "Garrett";
function sayHello(name) {
console.log(`Hello, ${name}
`);
}
sayHello(myName);
sayHello()
Call Stack
const myName = "Garrett";
function sayHello(name) {
console.log(`Hello, ${name}
`);
}
sayHello(myName);
sayHello()
console.log(“Garrett”)
Call Stack
const myName = "Garrett";
function sayHello(name) {
console.log(`Hello, ${name}
`);
}
sayHello(myName);
sayHello()
Call Stack
const myName = "Garrett";
function sayHello(name) {
console.log(`Hello, ${name}
`);
}
sayHello(myName);
What about
asynchronous code?
Some examples…
• Code that runs on a delay (setTimeout,
setInterval, etc.) 🕐
• Code that requests data from a webpage/API
(Ajax, Fetch, etc.) 🌐
• Code that requests data from a database or
filesystem (typically run server-side) 🗂
Some callback-based code
function sayHello(name) {
console.log(`Hello, ${name}`);
}
setTimeout(() => {
sayHello("Garrett")
}, 2000)
Call Stack Browser
APIs
Callback Queue
setTimeout()
Call Stack Browser
APIs
Callback Queue
setTimeout()
Call Stack Browser
APIs
Callback Queue
() => {}
Call Stack Browser
APIs
Callback Queue
() => {}
Call Stack Browser
APIs
Callback Queue
() => {}
sayHello()
Call Stack Browser
APIs
Callback Queue
() => {}
sayHello()
console.log()
Call Stack Browser
APIs
Callback Queue
() => {}
sayHello()
Call Stack Browser
APIs
Callback Queue
() => {}
Call Stack Browser
APIs
Callback Queue
A few choices
• Callbacks
• Promises
• Async/Await
Callbacks
Callbacks
• Just functions!
• Not any kind of special part of Javascript
• Function passed into another function to be run
on the result
Synchronous Example
function sayHello(person, response) {
console.log(`Hello, ${person}!`)
response()
}
function sayHiBack() {
console.log('Hi! Good to see you!')
}
sayHello('DevWeek', sayHiBack)
Synchronous Example
function sayHello(person, response) {
console.log(`Hello, ${person}!`)
response()
}
function sayHiBack() {
console.log('Hi! Good to see you!')
}
sayHello('DevWeek', sayHiBack)
// 'Hello, DevWeek!'
// 'Hi! Good to see you!
Some common examples
• Javascript APIs like setTimeout, setInterval, etc.
• jQuery AJAX requests
• Node-style callbacks
• Often in the form of (err, data) => { … }
The AJAX Way
$.ajax({
url: 'https://jsonplaceholder.typicode.com/users',
success: function(data) {
console.log(data);
},
error: function(request, error) {
console.log(error);
},
dataType: ‘json’
});
The AJAX Way
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},…
]
Advantages
• Straightforward (at first)
• Many examples
• Comfortable
Disadvantages
• Debugging
• Readability
• Complexity
Callback Hell
$.ajax({
url: 'https://jsonplaceholder.typicode.com/users',
success: function(data) {
const target = data[4];
const id = target.id;
$.ajax({
url: `https://jsonplaceholder.typicode.com/posts?userId=${id}`,
success: function(data) {
console.log(data)
},
error: function(request, error) {
console.log(error)
},
dataType: 'json'
});
},
error: function(request, error) {
console.log(error)
},
dataType: 'json'
});
Promises
What is a promise?
• “An object that represents the eventual
completion or failure of an asynchronous
operation”
• A much easier way to work with async code
Let’s look inside
The Promise Constructor
const newPromise = new Promise((resolve, reject) => {
// asynchronous operation here
if (error) {
reject(error); // rejected
}
resolve(someValue); // fulfilled
});
Why are they useful?
• Quicker to write
• Easily “chainable”
• Better at dealing with complex situations
Callback Hell
$.ajax({
url: 'https://jsonplaceholder.typicode.com/users',
success: function(data) {
const target = data[4];
const id = target.id;
$.ajax({
url: `https://jsonplaceholder.typicode.com/posts?userId=${id}`,
success: function(data) {
console.log(data)
},
error: function(request, error) {
console.log(error)
},
dataType: 'json'
});
},
error: function(request, error) {
console.log(error)
},
dataType: 'json'
});
With Promises…
fetch("https://jsonplaceholder.typicode.com/users")
.then(result => result.json())
.then(data => {
let id = data[4].id;
return fetch(`https://jsonplaceholder.typicode.com/
posts?userId=${id}`);
})
.then(result => result.json())
.then(posts => console.log(posts))
Building blocks
• .then()
• .catch()
• .finally()
Making a promise
• Native ES6 constructor
• Node’s util.promisify()
• Third-party libraries like Bluebird
Example
const wait = function(ms, value) {
return new Promise (function(resolve) {
setTimeout(() => resolve(value), ms)
})
}
wait(2000, "hello").then(result =>
{console.log(result)})
What about the event
loop?
Not quite the same
• Micro task queue
• .then()/.catch() statements take priority over
macro-tasks (like setTimeout or browser events)
that move into the normal event queue
Example
console.log('start');
setTimeout(function() {
console.log('end of timeout')
},0);
Promise.resolve("result of promise")
.then(value => console.log(value));
Example
console.log('start');
setTimeout(function() {
console.log('end of timeout')
},0);
Promise.resolve("result of promise")
.then(value => console.log(value));
// "start"
// "result of promise"
// "end of timeout"
Why is this useful?
• Granular control over the order of async actions
• Control over the state of the DOM/events
A few additional methods
• Promise.all( … )
• Array of results once all promises have resolved
• Promise.race( … )
• Result of first promise to resolve (or reason if
promise rejects)
• Promise.allSettled( … )
• Array of statuses of all promises (not results)
Promise.all()
fetch("https://jsonplaceholder.typicode.com/users")
.then(result => result.json())
.then(data => {
let id = data[4].id;
return fetch(`https://jsonplaceholder.typicode.com/posts?userId=${id}`);
})
.then(result => result.json())
.then(posts => posts.map(post => fetch(`https://jsonplaceholder.typicode.com/
comments?postId=${post.id}`)))
.then(promiseArr => Promise.all(promiseArr))
.then(responses => Promise.all(responses.map(response => response.json())))
.then(results => console.log(results))
Async/Await
Background
• Introduced in ES8
• Similar to generators
• Allows async code to be written more like
synchronous code
• Syntactic sugar on top of promises
Example
async function sayHello() {
return "Hello!"
}
sayHello().then(response => console.log(response))
Example
async function sayHello() {
return "Hello!"
}
sayHello().then(response => console.log(response))
// logs "Hello!"
Async Functions
• Must be declared with the async keyword
• Always return a promise
• Pause their execution when they hit the await
keyword
Refactoring
async function getComments() {
let users = await fetch("https://jsonplaceholder.typicode.com/users");
users = await users.json();
let id = users[4].id;
let posts = await fetch(`https://jsonplaceholder.typicode.com/posts?userId=${id}`);
posts = await posts.json();
let promiseArr = posts.map(post => await fetch( `https://jsonplaceholder.typicode.com/
comments?postId=${post.id}`));
let comments = await Promise.all(promiseArr)
comments = await Promise.all(comments.map(comment => comment.json()))
console.log(comments)
}
getComments()
Even cleaner
async function getComments() {
let users = await (await fetch("https://jsonplaceholder.typicode.com/users")).json();
let id = users[4].id;
let posts = await (await fetch(`https://jsonplaceholder.typicode.com/posts?userId=$
{id}`)).json()
let comments = await Promise.all(
posts.map(async (post) => await (await fetch( `https://jsonplaceholder.typicode.com/
comments?postId=${post.id}`)).json())
)
console.log(comments)
}
getComments()
Pros/Cons
• Lets us write code that looks and feels more
synchronous
• Allows us to easily use try/catch blocks inside of
async functions
• Sequential nature of code can make successive
async actions take longer
• Can use Promise.all() to avoid this
Wrapping Up
Takeaways
• Understand the event loop and how
asynchronous code is executed in Javascript
• Understand callbacks and their pros & cons
• Understand the pros & cons of promises and
async/await
• Understand how to refactor old code to utilize
newer methods
Thanks!

More Related Content

PDF
Asynchronous JavaScript Programming with Callbacks & Promises
Hùng Nguyễn Huy
 
PDF
Asynchronous JavaScript Programming
Haim Michael
 
PPT
Javascript arrays
Hassan Dar
 
PPTX
Introduction to Node.js
Vikash Singh
 
PPTX
JavaScript Event Loop
Designveloper
 
PPT
Introduction to Javascript
Amit Tyagi
 
PPT
Hati Bapa
Edi Zakaria
 
PDF
requirement gathering
SaeedMat
 
Asynchronous JavaScript Programming with Callbacks & Promises
Hùng Nguyễn Huy
 
Asynchronous JavaScript Programming
Haim Michael
 
Javascript arrays
Hassan Dar
 
Introduction to Node.js
Vikash Singh
 
JavaScript Event Loop
Designveloper
 
Introduction to Javascript
Amit Tyagi
 
Hati Bapa
Edi Zakaria
 
requirement gathering
SaeedMat
 

What's hot (20)

PPTX
Typescript ppt
akhilsreyas
 
PPTX
JavaScript Promises
L&T Technology Services Limited
 
PPTX
Node.js Express
Eyal Vardi
 
PDF
ES6 presentation
ritika1
 
PDF
TypeScript Introduction
Dmitry Sheiko
 
PDF
Introduction into ES6 JavaScript.
boyney123
 
PDF
3. Java Script
Jalpesh Vasa
 
PDF
Introducing Async/Await
Valeri Karpov
 
PPT
JavaScript Tutorial
Bui Kiet
 
PDF
Understanding react hooks
Samundra khatri
 
PPTX
Getting started with typescript
C...L, NESPRESSO, WAFAASSURANCE, SOFRECOM ORANGE
 
PDF
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Edureka!
 
PDF
JavaScript: Variables and Functions
Jussi Pohjolainen
 
PDF
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
PDF
JavaScript Promises
Derek Willian Stavis
 
PDF
Basics of JavaScript
Bala Narayanan
 
PPTX
TypeScript Overview
Aniruddha Chakrabarti
 
PDF
Clean code
Arturo Herrero
 
PPT
TypeScript Presentation
Patrick John Pacaña
 
PPTX
Lab #2: Introduction to Javascript
Walid Ashraf
 
Typescript ppt
akhilsreyas
 
JavaScript Promises
L&T Technology Services Limited
 
Node.js Express
Eyal Vardi
 
ES6 presentation
ritika1
 
TypeScript Introduction
Dmitry Sheiko
 
Introduction into ES6 JavaScript.
boyney123
 
3. Java Script
Jalpesh Vasa
 
Introducing Async/Await
Valeri Karpov
 
JavaScript Tutorial
Bui Kiet
 
Understanding react hooks
Samundra khatri
 
Getting started with typescript
C...L, NESPRESSO, WAFAASSURANCE, SOFRECOM ORANGE
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Edureka!
 
JavaScript: Variables and Functions
Jussi Pohjolainen
 
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
JavaScript Promises
Derek Willian Stavis
 
Basics of JavaScript
Bala Narayanan
 
TypeScript Overview
Aniruddha Chakrabarti
 
Clean code
Arturo Herrero
 
TypeScript Presentation
Patrick John Pacaña
 
Lab #2: Introduction to Javascript
Walid Ashraf
 
Ad

Similar to Intro to Asynchronous Javascript (20)

PPTX
asyncjavascript.pptxdgdsgdffgfdgfgfgfdgfdgf
zmulani8
 
PPTX
How to perform debounce in react
BOSC Tech Labs
 
PPTX
JavaScript Multithread or Single Thread.pptx
RAHITNATH
 
PPTX
Avoiding Callback Hell with Async.js
cacois
 
PDF
Asynchronous web apps with the Play Framework 2.0
Oscar Renalias
 
KEY
Node.js
Mat Schaffer
 
PPTX
Async Redux Actions With RxJS - React Rally 2016
Ben Lesh
 
PDF
How to make Ajax work for you
Simon Willison
 
PPTX
Introduction to Vert.x
Yiguang Hu
 
KEY
Writing robust Node.js applications
Tom Croucher
 
PPTX
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola
 
PDF
An opinionated intro to Node.js - devrupt hospitality hackathon
Luciano Mammino
 
PPT
JS everywhere 2011
Oleg Podsechin
 
KEY
Playing With Fire - An Introduction to Node.js
Mike Hagedorn
 
PDF
Asynchronous development in JavaScript
Amitai Barnea
 
PPTX
Asynchronous Web Programming with HTML5 WebSockets and Java
James Falkner
 
PDF
Serverless Ballerina
Ballerina
 
PPT
Expert JavaScript tricks of the masters
Ara Pehlivanian
 
PPTX
Event-driven IO server-side JavaScript environment based on V8 Engine
Ricardo Silva
 
PDF
Intro to jquery
Dan Pickett
 
asyncjavascript.pptxdgdsgdffgfdgfgfgfdgfdgf
zmulani8
 
How to perform debounce in react
BOSC Tech Labs
 
JavaScript Multithread or Single Thread.pptx
RAHITNATH
 
Avoiding Callback Hell with Async.js
cacois
 
Asynchronous web apps with the Play Framework 2.0
Oscar Renalias
 
Node.js
Mat Schaffer
 
Async Redux Actions With RxJS - React Rally 2016
Ben Lesh
 
How to make Ajax work for you
Simon Willison
 
Introduction to Vert.x
Yiguang Hu
 
Writing robust Node.js applications
Tom Croucher
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola
 
An opinionated intro to Node.js - devrupt hospitality hackathon
Luciano Mammino
 
JS everywhere 2011
Oleg Podsechin
 
Playing With Fire - An Introduction to Node.js
Mike Hagedorn
 
Asynchronous development in JavaScript
Amitai Barnea
 
Asynchronous Web Programming with HTML5 WebSockets and Java
James Falkner
 
Serverless Ballerina
Ballerina
 
Expert JavaScript tricks of the masters
Ara Pehlivanian
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Ricardo Silva
 
Intro to jquery
Dan Pickett
 
Ad

Recently uploaded (20)

PPTX
Coupa-Overview _Assumptions presentation
annapureddyn
 
PDF
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PDF
Architecture of the Future (09152021)
EdwardMeyman
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PPT
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
Beyond Automation: The Role of IoT Sensor Integration in Next-Gen Industries
Rejig Digital
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
Coupa-Overview _Assumptions presentation
annapureddyn
 
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
Architecture of the Future (09152021)
EdwardMeyman
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
Software Development Methodologies in 2025
KodekX
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Beyond Automation: The Role of IoT Sensor Integration in Next-Gen Industries
Rejig Digital
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 

Intro to Asynchronous Javascript