Asynchronous JavaScript
https://slides.com/dtauer/hdc2017-async
Dustin Tauer
dustin@easelsolutions.com
@dtauer
Asynchronous JavaScript
- Callbacks
- Promises
- Async / Await
Callbacks
Callback Hell
// When the button is clicked, load some images (with jQuery)
// and make them clickable
button.addEventListener('click', function(){
$.ajax({url:'/some/endpoint/', success:
function(result){
var image = result.images
images.forEach(function(image){
image.addEventListener('click', function(){
// Should we load some more data?
// Continue the Pyramid?
})
})
}
})
})
The Pyramid of Doom
Callbacks are not bad...
The just make it difficult to write complex code
Arrow Functions
Not related to anything asynchronous, but I want to mention them
// Old Syntax
const f1 = function(){
}
// Arrow Function
const f2 = () => {
}
// No arguements
const f3 = () => {
}
// One arguement
const f4 = arg1 => {
}
// Two arguement
const f4 = (arg1, arg2) => {
}
// Drop the return statement
const f6 = function(){
return 'something'
}
const f7 = () => 'something'
imageList.forEach( image => {
})
imageList.forEach( function(image) {
})
Promises
Promises (ES6)
"Like taking a ticket at the deli counter"
Introduction
https://developers.google.com/web/fundamentals/getting-started/primers/promises
Not supported in IE11, but here's a polyfill
function getSomeTurkey(){
return new Promise(resolve, reject){
// When it your number is called
resolve()
})
}
getSomeTurkey()
.then((result) => {
// What would you like?
})
Async/Await
Async / Await (ES7)
"Making asynchronous code, look synchronous"
Introduction
https://css-tricks.com/using-es2017-async-functions/
Tips & Tricks
http://2ality.com/2016/10/async-function-tips.html
https://developers.google.com/web/fundamentals/getting-started/primers/async-functions
Why you should care
https://blog.patricktriest.com/what-is-async-await-why-should-you-care/
async function getData() {
let data = await fetch('http://sample-api.com/posts')
console.log(data)
}
getData()
Understanding async/await in 7 seconds
I want it now!
Thanks!
https://slides.com/dtauer/hdc2017-async
HDC 2017 - Asynchronous JavaScript
By Dustin Tauer
HDC 2017 - Asynchronous JavaScript
- 1,359