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"

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"

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