SlideShare une entreprise Scribd logo
1  sur  62
Télécharger pour lire hors ligne
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!

Contenu connexe

Tendances

TypeScript Presentation
TypeScript PresentationTypeScript Presentation
TypeScript Presentation
Patrick John Pacaña
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
Adieu
 

Tendances (20)

TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the pain
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
TypeScript Presentation
TypeScript PresentationTypeScript Presentation
TypeScript Presentation
 
What is component in reactjs
What is component in reactjsWhat is component in reactjs
What is component in reactjs
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
Callback Function
Callback FunctionCallback Function
Callback Function
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practices
 
React hooks
React hooksReact hooks
React hooks
 
Modern JS with ES6
Modern JS with ES6Modern JS with ES6
Modern JS with ES6
 
Asynchronous javascript
 Asynchronous javascript Asynchronous javascript
Asynchronous javascript
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch API
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern Javascript
 
State management in react applications (Statecharts)
State management in react applications (Statecharts)State management in react applications (Statecharts)
State management in react applications (Statecharts)
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
 

Similaire à Intro to Asynchronous Javascript

Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 

Similaire à Intro to Asynchronous Javascript (20)

How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in react
 
JavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxJavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptx
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0
 
Node.js
Node.jsNode.js
Node.js
 
Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016
 
How to make Ajax work for you
How to make Ajax work for youHow to make Ajax work for you
How to make Ajax work for you
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.x
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
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...
 
An opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathonAn opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathon
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Playing With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsPlaying With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.js
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
 
Asynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and JavaAsynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and Java
 
Serverless Ballerina
Serverless BallerinaServerless Ballerina
Serverless Ballerina
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
Intro to jquery
Intro to jqueryIntro to jquery
Intro to jquery
 
JavaScript JQUERY AJAX
JavaScript JQUERY AJAXJavaScript JQUERY AJAX
JavaScript JQUERY AJAX
 

Dernier

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Dernier (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
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...
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
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
 
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
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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)
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

Intro to Asynchronous Javascript