SlideShare a Scribd company logo
1 of 28
Understanding
async/await
in Javascript
Hao Luo
Sr Technical Evangelist
Microsoft
@howlowck
About Me
Overview
• Single-Threaded
• Callbacks
• Promises
• Generators
• Async/Await
Heads Up
• No ES6 syntactic sugar
• Trivial Demos
• setTimeout or simple APIs
• Perfect World (no errors)
NodeJS
http://bit.ly/original-nodejs
http://bit.ly/original-nodejs-slides
We’re taught I/O with this:
puts("Enter your name: ");
var name = gets();
puts("Name: " + name);
We’re taught to demand input and do nothing until we have
it.
Code like
puts("Enter your name: ");
gets(function (name) {
puts("Name: " + name);
});
is rejected as too complicated.
Callbacks
Ryan’s Example:
puts("Enter your name: ");
gets(function (name) {
puts("Name: " + name);
});
var form = document.querySelector('#login')
form.addEventListener('submit', function () {
doSomething()
doSomethingElse()
})
http://bit.ly/explaining-async
01
✔️7.6+ ✔️8.0.* ❌8.1.0 ❌8.1.1 ✔️8.1.2
Call Stack
console.log(getAnswer(3))
getAnswer(3)
inWords(4)
function inWords (answer) {
return 'The Answer is ' + answer
}
function getAnswer (num) {
return inWords(num + 1)
}
let input = 3
console.log(getAnswer(input))
main()
Run to completion
pretendToThink(input)
setTimeout(cb)getAnswer(3)console.log('thinking...')
inWords(4)
function inWords (answer) {
return 'The Answer is ' + answer
}
function getAnswer (num) {
return inWords(num + 1)
}
function pretendToThink (num) {
setTimeout(function cb () {
console.log(getAnswer(num))
}, 8000)
console.log('thinking...')
}
let input = 3
pretendToThink(input)
Call Stack Web API / Node C++
main()
cb
Callback Queue
console.log(getAnswer(3))
cb()
cb
Event Loop
Concurrency
Phew… That was a lot…
• When we talk about Single-Threaded, it means there is only one call
stack and one event loop.
• Event Loop watches the callback queue and the call stack
• If the call stack is empty, and there is something in the callback
queue, the Event Loop puts the callback function in the call stack.
http://bit.ly/eventloop-explained
Philip Roberts
Callback Hell
Ryan’s Example:
puts("Enter your name: ");
gets(function (name) {
puts("Name: " + name);
});
Ryan’s Extended Example:
puts('Enter your name: ')
gets(function (name) {
puts('Name: ' + name)
puts('Enter your email: ')
gets(function (email) {
puts('Email: ' + name)
puts('Enter your phone number: ')
gets(function (phone) {
puts('Phone: ' + phone)
puts('Enter your birth date: ')
gets(function (birthDate) {
puts('Birth Date: ' + birthDate)
})
})
})
})
02
Async Impact
ES2016 async/await
puts('Enter your name: ')
gets(function (name) {
puts('Name: ' + name)
puts('Enter your email: ')
gets(function (email) {
puts('Email: ' + name)
puts('Enter your phone number: ')
gets(function (phone) {
puts('Phone: ' + phone)
puts('Enter your birth date: ')
gets(function (birthDate) {
puts('Birth Date: ' + birthDate)
})
})
})
})
async function program () {
puts('Enter your name: ')
var name = await gets()
puts('Name: ' + name)
puts('Enter your Email: ')
var email = await gets()
puts('Email: ' + email)
puts('Enter your Phone: ')
var phone = await gets()
puts('Phone: ' + phone)
puts('Enter your Birth Date: ')
var date = await gets()
puts('Date: ' + date)
}
Promises
• A Promise is a value that guarantees a future value.
• In Javascript ES6, a Promise is an object that has a then method on it.
• When instantiating a Promise Object, it takes in a function that has
two callback parameters (commonly known as resolve, and
reject)
Promises Overview
var requestName = new Promise(function (resolve) {
puts('Enter Your Name: ')
gets(function (name) {
resolve(name)
})
})
requestName.then(function (name) {
console.log(name)
})
var requestName = new Promise(function (resolve) {
puts('Enter Your Name: ')
gets(function (name) {
resolve(name)
})
})
requestName.then(function (name) {
console.log(name)
})
The then method
• The then method always returns a Promise
• The then method takes in two functions as parameters
• The first function is the resolve function
function requestName () {
return new Promise(function (resolve) {
puts('Enter Your Name: ')
gets(function (name) {
resolve(name)
})
})
}
function requestEmail () {
return new Promise(function (resolve) {
puts('Enter Your Email: ')
gets(function (email) {
resolve(email)
})
})
}
… …
puts('Enter your name: ')
gets(function (name) {
puts('Name: ' + name)
puts('Enter your email: ')
gets(function (email) {
puts('Email: ' + name)
puts('Enter your phone number: ')
gets(function (phone) {
puts('Phone: ' + phone)
puts('Enter your birth date: ')
gets(function (birthDate) {
puts('Birth Date: ' + birthDate)
})
})
})
})
requestName()
.then(function (name) {
puts('Name: ' + name)
})
.then(requestEmail)
.then(function (email) {
puts('Email: ' + email)
})
.then(requestPhone)
.then(function (phone) {
puts('Phone: ' + phone)
})
.then(requestBirthDate)
.then(function (birthDate) {
puts('Birth Date: ' + birthDate)
})
Extended Example 03
Generators
Generator Function
• function * and yield
• A generator function returns an iterator object
• an iterator object has a next method on it.
• The next method runs/continues the generator function up to yield
• The next method returns an object that has two parameters value and done
function * countDown () {
puts('Fuel Check')
yield 3
puts('Engine Check')
yield 2
puts('Electrical Check')
yield 1
puts('Launching...')
}
Generator
Scope
Iterator
Scope
var iterator = countDown()
var yieldedResult = iterator.next()
puts(yieldedResult.value)
yieldedResult = iterator.next()
puts(yieldedResult.value)
yieldedResult = iterator.next()
puts(yieldedResult.value)
yieldedResult = iterator.next()
puts(yieldedResult.value)
Basic Example
// object that has a next method on it
// { value: 3, done: false }
// { value: 2, done: false }
// { value: 1, done: false }
// { value: undefined, done: true }
• function * and yield
• A generator function returns an iterator object
• an iterator object has a next method on it.
• The next method runs/continues the generator function up to yield
• The next method returns an object with two params value and done
04
Special Yield
function * countDown () {
puts('Fuel Check')
yield 3
puts('Engine Check')
yield 2
puts('Electrical Check')
yield 1
puts('Launching...')
}
Generator
Scope
Iterator
Scope
var iterator = countDown()
var yieldedResult = iterator.next()
puts(yieldedResult.value)
yieldedResult = iterator.next()
puts(yieldedResult.value)
yieldedResult = iterator.next()
puts(yieldedResult.value)
yieldedResult = iterator.next()
puts(yieldedResult.value)
var engineStatus = yield 3yield 3
// { value: 3, done: false }
var engineCheck = {everythingGood: true}
yieldedResult = iterator.next(engineCheck)
// {everythingGood: true}
• The yield keyword can produce a
value
• The value is passed in by the following
next method call
05
Generators + Promises
function requestName () {
return new Promise(function (resolve) {
callbackGets(function (name) {
resolve(name)
})
})
}
function * program () {
puts('Enter Your Name: ')
var name = yield requestName()
puts('Name: ' + name)
puts('Enter Your Email: ')
var email = yield requestEmail()
puts('Email: ' + email)
puts('Enter Your Phone: ')
var phone = yield requestPhone()
puts('Phone' + phone)
puts('Enter Your Birth Date: ')
var date = yield requestBirthDate()
puts('Birth Date' + date)
}
var running = program()
running.next()
.value
.then(function (name) {
running.next(name)
.value
.then(function (email) {
running.next(email)
.value
.then(function (phone) {
running.next(phone)
.value
.then(function (birthDate) {
running.next(birthDate)
})
})
})
})
function requestEmail () {
return new Promise(function (resolve) {
callbackGets(function (email) {
resolve(email)
})
})
}
function requestPhone () {
return new Promise(function (resolve) {
callbackGets(function (phone) {
resolve(phone)
})
})
}
function requestBirthDate () {
return new Promise(function (resolve) {
callbackGets(function (birthDate) {
resolve(birthDate)
})
})
}
// iterator object
// {done: false, value: Promise}
// Promise (has a then method)
// then takes the callback
// {done: false, value: Promise}
// Promise (has a then method)
06
function requestBirthDate () {
return new Promise(function (resolve) {
callbackGets(function (birthDate) {
resolve(birthDate)
})
})
}
function requestPhone () {
return new Promise(function (resolve) {
callbackGets(function (phone) {
resolve(phone)
})
})
}
function requestEmail () {
return new Promise(function (resolve) {
callbackGets(function (email) {
resolve(email)
})
})
}
function requestName () {
return new Promise(function (resolve) {
callbackGets(function (name) {
resolve(name)
})
})
}
data
data
data
data
data
Refactoring Promises
name
name
email
email
phone
phone
birthDate
birthDate
data
data
data
function gets () {
return new Promise(function (resolve, reject) {
callbackGets(function (data) {
resolve(data)
})
})
}
07
Refactoring Runner
var running = program()
running.next()
.value
.then(function (name) {
running.next(name)
.value
.then(function (email) {
running.next(email)
.value
.then(function (phone) {
running.next(phone)
.value
.then(function (birthDate) {
running.next(birthDate)
})
})
})
})
// iterator object
// {done: false, value: Promise}
// Promise (has a then method)
// then takes the callback
// {done: false, value: Promise}
// Promise (has a then method)
function run (generatorFunc) {
}
run(program)
07
var iterator = generatorFunc() // iterator object
var yieldedObject
// undefined-> name -> email -> phone -> birthDate
function loop (resolvedValue) {
}
loop() // start the loop
yieldedObject = iterator.next(resolvedValue)
// yieldObject == {done: false, value: Promise}
if (!yieldedObject.done) {
yieldedObject.value.then(loop)
}
Async/await vs Generator+Promises
async function program () {
puts('Enter your name: ')
var name = await gets()
puts('Name: ' + name)
puts('Enter your Email: ')
var email = await gets()
puts('Email: ' + email)
puts('Enter your Phone: ')
var phone = await gets()
puts('Phone: ' + phone)
puts('Enter your Birth Date: ')
var date = await gets()
puts('Date: ' + date)
}
function * program () {
puts('Enter your Name: ')
var name = yield gets()
puts('Name: ' + name)
puts('Enter your Email: ')
var email = yield gets()
puts('Email: ' + email)
puts('Enter your Phone: ')
var phone = yield gets()
puts('Phone: ' + phone)
puts('Enter your Birth Date: ')
var date = yield gets()
puts('Birth Date: ' + date)
}
07
10
Fetch API Example
function * program () {
puts('Enter your name: ‘)
var name = yield requestName()
puts('Fetch from Server...’)
var burgerName = yield fetchRandomBurgerName()
puts(name + ' wants a ' + burgerName)
}
runs(program)
var runs = require('./lib/runs')
var fetch = require('node-fetch')
var gets = require('./lib/gets')
var puts = require('./lib/puts')
var apiRoute = 'https://bobsburger-names.azurewebsites.net/api/random'
function requestName () {
return new Promise(gets)
}
function fetchRandomBurgerName () {
return fetch(apiRoute)
.then(function (res) {
return res.json()
})
.then(function (data) {
return data.name
})
}
Closing Thoughts
• Understand the basics by looking behind the curtain
• Resist the urge to rage quit
Resources & Questions?
• http://bit.ly/original-nodejs
• http://bit.ly/original-nodejs-slides
• http://bit.ly/eventloop-explained
• https://davidwalsh.name/es6-generators
• https://github.com/howlowck/explaining-async
@HowLowCK

More Related Content

What's hot

The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181Mahmoud Samir Fayed
 
The Ring programming language version 1.7 book - Part 42 of 196
The Ring programming language version 1.7 book - Part 42 of 196The Ring programming language version 1.7 book - Part 42 of 196
The Ring programming language version 1.7 book - Part 42 of 196Mahmoud Samir Fayed
 
The Ring programming language version 1.9 book - Part 47 of 210
The Ring programming language version 1.9 book - Part 47 of 210The Ring programming language version 1.9 book - Part 47 of 210
The Ring programming language version 1.9 book - Part 47 of 210Mahmoud Samir Fayed
 
The Ring programming language version 1.10 book - Part 50 of 212
The Ring programming language version 1.10 book - Part 50 of 212The Ring programming language version 1.10 book - Part 50 of 212
The Ring programming language version 1.10 book - Part 50 of 212Mahmoud Samir Fayed
 
The Ring programming language version 1.5.3 book - Part 40 of 184
The Ring programming language version 1.5.3 book - Part 40 of 184The Ring programming language version 1.5.3 book - Part 40 of 184
The Ring programming language version 1.5.3 book - Part 40 of 184Mahmoud Samir Fayed
 
Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2Technopark
 
The Ring programming language version 1.5.4 book - Part 38 of 185
The Ring programming language version 1.5.4 book - Part 38 of 185The Ring programming language version 1.5.4 book - Part 38 of 185
The Ring programming language version 1.5.4 book - Part 38 of 185Mahmoud Samir Fayed
 
The Ring programming language version 1.4.1 book - Part 11 of 31
The Ring programming language version 1.4.1 book - Part 11 of 31The Ring programming language version 1.4.1 book - Part 11 of 31
The Ring programming language version 1.4.1 book - Part 11 of 31Mahmoud Samir Fayed
 
ZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaWiem Zine Elabidine
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2Mouna Guru
 
Async all around us (promises)
Async all around us (promises)Async all around us (promises)
Async all around us (promises)Francisco Ferreira
 
The Ring programming language version 1.4 book - Part 9 of 30
The Ring programming language version 1.4 book - Part 9 of 30The Ring programming language version 1.4 book - Part 9 of 30
The Ring programming language version 1.4 book - Part 9 of 30Mahmoud Samir Fayed
 
The Ring programming language version 1.2 book - Part 30 of 84
The Ring programming language version 1.2 book - Part 30 of 84The Ring programming language version 1.2 book - Part 30 of 84
The Ring programming language version 1.2 book - Part 30 of 84Mahmoud Samir Fayed
 
The Ring programming language version 1.3 book - Part 43 of 88
The Ring programming language version 1.3 book - Part 43 of 88The Ring programming language version 1.3 book - Part 43 of 88
The Ring programming language version 1.3 book - Part 43 of 88Mahmoud Samir Fayed
 
The Ring programming language version 1.5.2 book - Part 14 of 181
The Ring programming language version 1.5.2 book - Part 14 of 181The Ring programming language version 1.5.2 book - Part 14 of 181
The Ring programming language version 1.5.2 book - Part 14 of 181Mahmoud Samir Fayed
 
The Ring programming language version 1.5 book - Part 3 of 31
The Ring programming language version 1.5 book - Part 3 of 31The Ring programming language version 1.5 book - Part 3 of 31
The Ring programming language version 1.5 book - Part 3 of 31Mahmoud Samir Fayed
 
The Ring programming language version 1.5.2 book - Part 32 of 181
The Ring programming language version 1.5.2 book - Part 32 of 181The Ring programming language version 1.5.2 book - Part 32 of 181
The Ring programming language version 1.5.2 book - Part 32 of 181Mahmoud Samir Fayed
 
Functional GUIs with F#
Functional GUIs with F#Functional GUIs with F#
Functional GUIs with F#Frank Krueger
 
The Ring programming language version 1.10 book - Part 31 of 212
The Ring programming language version 1.10 book - Part 31 of 212The Ring programming language version 1.10 book - Part 31 of 212
The Ring programming language version 1.10 book - Part 31 of 212Mahmoud Samir Fayed
 

What's hot (20)

The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181
 
The Ring programming language version 1.7 book - Part 42 of 196
The Ring programming language version 1.7 book - Part 42 of 196The Ring programming language version 1.7 book - Part 42 of 196
The Ring programming language version 1.7 book - Part 42 of 196
 
The Ring programming language version 1.9 book - Part 47 of 210
The Ring programming language version 1.9 book - Part 47 of 210The Ring programming language version 1.9 book - Part 47 of 210
The Ring programming language version 1.9 book - Part 47 of 210
 
The Ring programming language version 1.10 book - Part 50 of 212
The Ring programming language version 1.10 book - Part 50 of 212The Ring programming language version 1.10 book - Part 50 of 212
The Ring programming language version 1.10 book - Part 50 of 212
 
The Ring programming language version 1.5.3 book - Part 40 of 184
The Ring programming language version 1.5.3 book - Part 40 of 184The Ring programming language version 1.5.3 book - Part 40 of 184
The Ring programming language version 1.5.3 book - Part 40 of 184
 
Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2
 
The Ring programming language version 1.5.4 book - Part 38 of 185
The Ring programming language version 1.5.4 book - Part 38 of 185The Ring programming language version 1.5.4 book - Part 38 of 185
The Ring programming language version 1.5.4 book - Part 38 of 185
 
The Ring programming language version 1.4.1 book - Part 11 of 31
The Ring programming language version 1.4.1 book - Part 11 of 31The Ring programming language version 1.4.1 book - Part 11 of 31
The Ring programming language version 1.4.1 book - Part 11 of 31
 
ZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in Scala
 
C++ practical
C++ practicalC++ practical
C++ practical
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2
 
Async all around us (promises)
Async all around us (promises)Async all around us (promises)
Async all around us (promises)
 
The Ring programming language version 1.4 book - Part 9 of 30
The Ring programming language version 1.4 book - Part 9 of 30The Ring programming language version 1.4 book - Part 9 of 30
The Ring programming language version 1.4 book - Part 9 of 30
 
The Ring programming language version 1.2 book - Part 30 of 84
The Ring programming language version 1.2 book - Part 30 of 84The Ring programming language version 1.2 book - Part 30 of 84
The Ring programming language version 1.2 book - Part 30 of 84
 
The Ring programming language version 1.3 book - Part 43 of 88
The Ring programming language version 1.3 book - Part 43 of 88The Ring programming language version 1.3 book - Part 43 of 88
The Ring programming language version 1.3 book - Part 43 of 88
 
The Ring programming language version 1.5.2 book - Part 14 of 181
The Ring programming language version 1.5.2 book - Part 14 of 181The Ring programming language version 1.5.2 book - Part 14 of 181
The Ring programming language version 1.5.2 book - Part 14 of 181
 
The Ring programming language version 1.5 book - Part 3 of 31
The Ring programming language version 1.5 book - Part 3 of 31The Ring programming language version 1.5 book - Part 3 of 31
The Ring programming language version 1.5 book - Part 3 of 31
 
The Ring programming language version 1.5.2 book - Part 32 of 181
The Ring programming language version 1.5.2 book - Part 32 of 181The Ring programming language version 1.5.2 book - Part 32 of 181
The Ring programming language version 1.5.2 book - Part 32 of 181
 
Functional GUIs with F#
Functional GUIs with F#Functional GUIs with F#
Functional GUIs with F#
 
The Ring programming language version 1.10 book - Part 31 of 212
The Ring programming language version 1.10 book - Part 31 of 212The Ring programming language version 1.10 book - Part 31 of 212
The Ring programming language version 1.10 book - Part 31 of 212
 

Similar to Understanding Async/Await in Javascript

Introduction to ECMAScript 2015
Introduction to ECMAScript 2015Introduction to ECMAScript 2015
Introduction to ECMAScript 2015Tomasz Dziuda
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to SwiftGiordano Scalzo
 
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...Domenic Denicola
 
jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyHuiyi Yan
 
Learning to code with Python! (Microsoft Virtual Academy).pptx
Learning to code with Python! (Microsoft Virtual Academy).pptxLearning to code with Python! (Microsoft Virtual Academy).pptx
Learning to code with Python! (Microsoft Virtual Academy).pptxJoshuaJoseph70
 
Learning to code with Python! (MVA).pptx
Learning to code with Python! (MVA).pptxLearning to code with Python! (MVA).pptx
Learning to code with Python! (MVA).pptxJoshuaJoseph70
 
Object-oriented Javascript
Object-oriented JavascriptObject-oriented Javascript
Object-oriented JavascriptDaniel Ku
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wildJoe Morgan
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web ModuleMorgan Cheng
 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages VictorSzoltysek
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitVaclav Pech
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVMVaclav Pech
 
All you need to know about JavaScript Functions
All you need to know about JavaScript FunctionsAll you need to know about JavaScript Functions
All you need to know about JavaScript FunctionsOluwaleke Fakorede
 
Multi client
Multi clientMulti client
Multi clientganteng8
 
WordPress Realtime - WordCamp São Paulo 2015
WordPress Realtime - WordCamp São Paulo 2015WordPress Realtime - WordCamp São Paulo 2015
WordPress Realtime - WordCamp São Paulo 2015Fernando Daciuk
 
Generics and Inference
Generics and InferenceGenerics and Inference
Generics and InferenceRichard Fox
 
An introduction to property-based testing
An introduction to property-based testingAn introduction to property-based testing
An introduction to property-based testingVincent Pradeilles
 
Automation in angular js
Automation in angular jsAutomation in angular js
Automation in angular jsMarcin Wosinek
 

Similar to Understanding Async/Await in Javascript (20)

Introduction to ECMAScript 2015
Introduction to ECMAScript 2015Introduction to ECMAScript 2015
Introduction to ECMAScript 2015
 
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
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...
 
jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journey
 
Learning to code with Python! (Microsoft Virtual Academy).pptx
Learning to code with Python! (Microsoft Virtual Academy).pptxLearning to code with Python! (Microsoft Virtual Academy).pptx
Learning to code with Python! (Microsoft Virtual Academy).pptx
 
Learning to code with Python! (MVA).pptx
Learning to code with Python! (MVA).pptxLearning to code with Python! (MVA).pptx
Learning to code with Python! (MVA).pptx
 
Object-oriented Javascript
Object-oriented JavascriptObject-oriented Javascript
Object-oriented Javascript
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wild
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
 
All you need to know about JavaScript Functions
All you need to know about JavaScript FunctionsAll you need to know about JavaScript Functions
All you need to know about JavaScript Functions
 
Multi client
Multi clientMulti client
Multi client
 
WordPress Realtime - WordCamp São Paulo 2015
WordPress Realtime - WordCamp São Paulo 2015WordPress Realtime - WordCamp São Paulo 2015
WordPress Realtime - WordCamp São Paulo 2015
 
Generics and Inference
Generics and InferenceGenerics and Inference
Generics and Inference
 
An introduction to property-based testing
An introduction to property-based testingAn introduction to property-based testing
An introduction to property-based testing
 
Automation in angular js
Automation in angular jsAutomation in angular js
Automation in angular js
 

Recently uploaded

#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 

Recently uploaded (20)

#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 

Understanding Async/Await in Javascript

  • 1. Understanding async/await in Javascript Hao Luo Sr Technical Evangelist Microsoft @howlowck
  • 3. Overview • Single-Threaded • Callbacks • Promises • Generators • Async/Await Heads Up • No ES6 syntactic sugar • Trivial Demos • setTimeout or simple APIs • Perfect World (no errors)
  • 4.
  • 5. NodeJS http://bit.ly/original-nodejs http://bit.ly/original-nodejs-slides We’re taught I/O with this: puts("Enter your name: "); var name = gets(); puts("Name: " + name); We’re taught to demand input and do nothing until we have it. Code like puts("Enter your name: "); gets(function (name) { puts("Name: " + name); }); is rejected as too complicated.
  • 6. Callbacks Ryan’s Example: puts("Enter your name: "); gets(function (name) { puts("Name: " + name); }); var form = document.querySelector('#login') form.addEventListener('submit', function () { doSomething() doSomethingElse() }) http://bit.ly/explaining-async 01 ✔️7.6+ ✔️8.0.* ❌8.1.0 ❌8.1.1 ✔️8.1.2
  • 7. Call Stack console.log(getAnswer(3)) getAnswer(3) inWords(4) function inWords (answer) { return 'The Answer is ' + answer } function getAnswer (num) { return inWords(num + 1) } let input = 3 console.log(getAnswer(input)) main() Run to completion
  • 8. pretendToThink(input) setTimeout(cb)getAnswer(3)console.log('thinking...') inWords(4) function inWords (answer) { return 'The Answer is ' + answer } function getAnswer (num) { return inWords(num + 1) } function pretendToThink (num) { setTimeout(function cb () { console.log(getAnswer(num)) }, 8000) console.log('thinking...') } let input = 3 pretendToThink(input) Call Stack Web API / Node C++ main() cb Callback Queue console.log(getAnswer(3)) cb() cb Event Loop Concurrency
  • 9. Phew… That was a lot… • When we talk about Single-Threaded, it means there is only one call stack and one event loop. • Event Loop watches the callback queue and the call stack • If the call stack is empty, and there is something in the callback queue, the Event Loop puts the callback function in the call stack.
  • 11. Callback Hell Ryan’s Example: puts("Enter your name: "); gets(function (name) { puts("Name: " + name); }); Ryan’s Extended Example: puts('Enter your name: ') gets(function (name) { puts('Name: ' + name) puts('Enter your email: ') gets(function (email) { puts('Email: ' + name) puts('Enter your phone number: ') gets(function (phone) { puts('Phone: ' + phone) puts('Enter your birth date: ') gets(function (birthDate) { puts('Birth Date: ' + birthDate) }) }) }) }) 02
  • 13. ES2016 async/await puts('Enter your name: ') gets(function (name) { puts('Name: ' + name) puts('Enter your email: ') gets(function (email) { puts('Email: ' + name) puts('Enter your phone number: ') gets(function (phone) { puts('Phone: ' + phone) puts('Enter your birth date: ') gets(function (birthDate) { puts('Birth Date: ' + birthDate) }) }) }) }) async function program () { puts('Enter your name: ') var name = await gets() puts('Name: ' + name) puts('Enter your Email: ') var email = await gets() puts('Email: ' + email) puts('Enter your Phone: ') var phone = await gets() puts('Phone: ' + phone) puts('Enter your Birth Date: ') var date = await gets() puts('Date: ' + date) }
  • 15. • A Promise is a value that guarantees a future value. • In Javascript ES6, a Promise is an object that has a then method on it. • When instantiating a Promise Object, it takes in a function that has two callback parameters (commonly known as resolve, and reject) Promises Overview var requestName = new Promise(function (resolve) { puts('Enter Your Name: ') gets(function (name) { resolve(name) }) }) requestName.then(function (name) { console.log(name) })
  • 16. var requestName = new Promise(function (resolve) { puts('Enter Your Name: ') gets(function (name) { resolve(name) }) }) requestName.then(function (name) { console.log(name) }) The then method • The then method always returns a Promise • The then method takes in two functions as parameters • The first function is the resolve function
  • 17. function requestName () { return new Promise(function (resolve) { puts('Enter Your Name: ') gets(function (name) { resolve(name) }) }) } function requestEmail () { return new Promise(function (resolve) { puts('Enter Your Email: ') gets(function (email) { resolve(email) }) }) } … … puts('Enter your name: ') gets(function (name) { puts('Name: ' + name) puts('Enter your email: ') gets(function (email) { puts('Email: ' + name) puts('Enter your phone number: ') gets(function (phone) { puts('Phone: ' + phone) puts('Enter your birth date: ') gets(function (birthDate) { puts('Birth Date: ' + birthDate) }) }) }) }) requestName() .then(function (name) { puts('Name: ' + name) }) .then(requestEmail) .then(function (email) { puts('Email: ' + email) }) .then(requestPhone) .then(function (phone) { puts('Phone: ' + phone) }) .then(requestBirthDate) .then(function (birthDate) { puts('Birth Date: ' + birthDate) }) Extended Example 03
  • 19. Generator Function • function * and yield • A generator function returns an iterator object • an iterator object has a next method on it. • The next method runs/continues the generator function up to yield • The next method returns an object that has two parameters value and done
  • 20. function * countDown () { puts('Fuel Check') yield 3 puts('Engine Check') yield 2 puts('Electrical Check') yield 1 puts('Launching...') } Generator Scope Iterator Scope var iterator = countDown() var yieldedResult = iterator.next() puts(yieldedResult.value) yieldedResult = iterator.next() puts(yieldedResult.value) yieldedResult = iterator.next() puts(yieldedResult.value) yieldedResult = iterator.next() puts(yieldedResult.value) Basic Example // object that has a next method on it // { value: 3, done: false } // { value: 2, done: false } // { value: 1, done: false } // { value: undefined, done: true } • function * and yield • A generator function returns an iterator object • an iterator object has a next method on it. • The next method runs/continues the generator function up to yield • The next method returns an object with two params value and done 04
  • 21. Special Yield function * countDown () { puts('Fuel Check') yield 3 puts('Engine Check') yield 2 puts('Electrical Check') yield 1 puts('Launching...') } Generator Scope Iterator Scope var iterator = countDown() var yieldedResult = iterator.next() puts(yieldedResult.value) yieldedResult = iterator.next() puts(yieldedResult.value) yieldedResult = iterator.next() puts(yieldedResult.value) yieldedResult = iterator.next() puts(yieldedResult.value) var engineStatus = yield 3yield 3 // { value: 3, done: false } var engineCheck = {everythingGood: true} yieldedResult = iterator.next(engineCheck) // {everythingGood: true} • The yield keyword can produce a value • The value is passed in by the following next method call 05
  • 22. Generators + Promises function requestName () { return new Promise(function (resolve) { callbackGets(function (name) { resolve(name) }) }) } function * program () { puts('Enter Your Name: ') var name = yield requestName() puts('Name: ' + name) puts('Enter Your Email: ') var email = yield requestEmail() puts('Email: ' + email) puts('Enter Your Phone: ') var phone = yield requestPhone() puts('Phone' + phone) puts('Enter Your Birth Date: ') var date = yield requestBirthDate() puts('Birth Date' + date) } var running = program() running.next() .value .then(function (name) { running.next(name) .value .then(function (email) { running.next(email) .value .then(function (phone) { running.next(phone) .value .then(function (birthDate) { running.next(birthDate) }) }) }) }) function requestEmail () { return new Promise(function (resolve) { callbackGets(function (email) { resolve(email) }) }) } function requestPhone () { return new Promise(function (resolve) { callbackGets(function (phone) { resolve(phone) }) }) } function requestBirthDate () { return new Promise(function (resolve) { callbackGets(function (birthDate) { resolve(birthDate) }) }) } // iterator object // {done: false, value: Promise} // Promise (has a then method) // then takes the callback // {done: false, value: Promise} // Promise (has a then method) 06
  • 23. function requestBirthDate () { return new Promise(function (resolve) { callbackGets(function (birthDate) { resolve(birthDate) }) }) } function requestPhone () { return new Promise(function (resolve) { callbackGets(function (phone) { resolve(phone) }) }) } function requestEmail () { return new Promise(function (resolve) { callbackGets(function (email) { resolve(email) }) }) } function requestName () { return new Promise(function (resolve) { callbackGets(function (name) { resolve(name) }) }) } data data data data data Refactoring Promises name name email email phone phone birthDate birthDate data data data function gets () { return new Promise(function (resolve, reject) { callbackGets(function (data) { resolve(data) }) }) } 07
  • 24. Refactoring Runner var running = program() running.next() .value .then(function (name) { running.next(name) .value .then(function (email) { running.next(email) .value .then(function (phone) { running.next(phone) .value .then(function (birthDate) { running.next(birthDate) }) }) }) }) // iterator object // {done: false, value: Promise} // Promise (has a then method) // then takes the callback // {done: false, value: Promise} // Promise (has a then method) function run (generatorFunc) { } run(program) 07 var iterator = generatorFunc() // iterator object var yieldedObject // undefined-> name -> email -> phone -> birthDate function loop (resolvedValue) { } loop() // start the loop yieldedObject = iterator.next(resolvedValue) // yieldObject == {done: false, value: Promise} if (!yieldedObject.done) { yieldedObject.value.then(loop) }
  • 25. Async/await vs Generator+Promises async function program () { puts('Enter your name: ') var name = await gets() puts('Name: ' + name) puts('Enter your Email: ') var email = await gets() puts('Email: ' + email) puts('Enter your Phone: ') var phone = await gets() puts('Phone: ' + phone) puts('Enter your Birth Date: ') var date = await gets() puts('Date: ' + date) } function * program () { puts('Enter your Name: ') var name = yield gets() puts('Name: ' + name) puts('Enter your Email: ') var email = yield gets() puts('Email: ' + email) puts('Enter your Phone: ') var phone = yield gets() puts('Phone: ' + phone) puts('Enter your Birth Date: ') var date = yield gets() puts('Birth Date: ' + date) } 07 10
  • 26. Fetch API Example function * program () { puts('Enter your name: ‘) var name = yield requestName() puts('Fetch from Server...’) var burgerName = yield fetchRandomBurgerName() puts(name + ' wants a ' + burgerName) } runs(program) var runs = require('./lib/runs') var fetch = require('node-fetch') var gets = require('./lib/gets') var puts = require('./lib/puts') var apiRoute = 'https://bobsburger-names.azurewebsites.net/api/random' function requestName () { return new Promise(gets) } function fetchRandomBurgerName () { return fetch(apiRoute) .then(function (res) { return res.json() }) .then(function (data) { return data.name }) }
  • 27. Closing Thoughts • Understand the basics by looking behind the curtain • Resist the urge to rage quit
  • 28. Resources & Questions? • http://bit.ly/original-nodejs • http://bit.ly/original-nodejs-slides • http://bit.ly/eventloop-explained • https://davidwalsh.name/es6-generators • https://github.com/howlowck/explaining-async @HowLowCK