SlideShare a Scribd company logo
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)
Understanding Async/Await in Javascript
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 (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
Mahmoud 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 196
Mahmoud 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 210
Mahmoud 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 212
Mahmoud 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 184
Mahmoud Samir Fayed
 
Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2
Technopark
 
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
Mahmoud 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 31
Mahmoud 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 Scala
Wiem Zine Elabidine
 
C++ practical
C++ practicalC++ practical
C++ practical
Rahul juneja
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2
Mouna 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 30
Mahmoud 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 84
Mahmoud 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 88
Mahmoud 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 181
Mahmoud 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 31
Mahmoud 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 181
Mahmoud 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 212
Mahmoud Samir Fayed
 
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
Mahmoud 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 196
Mahmoud 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 210
Mahmoud 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 212
Mahmoud 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 184
Mahmoud Samir Fayed
 
Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2
Technopark
 
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
Mahmoud 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 31
Mahmoud 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 Scala
Wiem Zine Elabidine
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2
Mouna 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 30
Mahmoud 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 84
Mahmoud 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 88
Mahmoud 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 181
Mahmoud 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 31
Mahmoud 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 181
Mahmoud 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 212
Mahmoud Samir Fayed
 

Similar to Understanding Async/Await in Javascript (20)

Introduction to ECMAScript 2015
Introduction to ECMAScript 2015Introduction to ECMAScript 2015
Introduction to ECMAScript 2015
Tomasz Dziuda
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
Giordano Scalzo
 
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
Iran Entrepreneurship Association
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
André Faria Gomes
 
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 journey
Huiyi 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).pptx
JoshuaJoseph70
 
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
JoshuaJoseph70
 
Object-oriented Javascript
Object-oriented JavascriptObject-oriented Javascript
Object-oriented Javascript
Daniel Ku
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wild
Joe Morgan
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
Morgan 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 fruit
Vaclav Pech
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
Vaclav 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 Functions
Oluwaleke Fakorede
 
Multi client
Multi clientMulti client
Multi client
ganteng8
 
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
Fernando Daciuk
 
Generics and Inference
Generics and InferenceGenerics and Inference
Generics and Inference
Richard Fox
 
An introduction to property-based testing
An introduction to property-based testingAn introduction to property-based testing
An introduction to property-based testing
Vincent Pradeilles
 
Automation in angular js
Automation in angular jsAutomation in angular js
Automation in angular js
Marcin Wosinek
 
Introduction to ECMAScript 2015
Introduction to ECMAScript 2015Introduction to ECMAScript 2015
Introduction to ECMAScript 2015
Tomasz Dziuda
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
Giordano 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 journey
Huiyi 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).pptx
JoshuaJoseph70
 
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
JoshuaJoseph70
 
Object-oriented Javascript
Object-oriented JavascriptObject-oriented Javascript
Object-oriented Javascript
Daniel Ku
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wild
Joe Morgan
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
Morgan 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 fruit
Vaclav Pech
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
Vaclav 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 Functions
Oluwaleke Fakorede
 
Multi client
Multi clientMulti client
Multi client
ganteng8
 
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
Fernando Daciuk
 
Generics and Inference
Generics and InferenceGenerics and Inference
Generics and Inference
Richard Fox
 
An introduction to property-based testing
An introduction to property-based testingAn introduction to property-based testing
An introduction to property-based testing
Vincent Pradeilles
 
Automation in angular js
Automation in angular jsAutomation in angular js
Automation in angular js
Marcin Wosinek
 
Ad

Recently uploaded (20)

Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Ad

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)
  • 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