#100Devs - Promises, Async, Node (cohort 02)

Class 30 of our Free Web Dev Bootcamp for folx affected by the pandemic. Join live T/Th 6:30pm ET leonnoel.com/twitch and ask questions here: leonnoel.com/discord

Skip to first slide
Slide 1 of 107

 

Promises, Async, Node

 

Leon Noel

#100Devs

Photo shoot fresh, looking like wealth
I'm 'bout to call the paparazzi on myself


Slide 2 of 107

Agenda


Slide 3 of 107

Questions

About last class or life


Slide 4 of 107

Checking In

Like and Retweet the Tweet

!checkin


Slide 5 of 107

Office Hours

SUNDAY
1:00pm EST


Slide 6 of 107

!newsletter


Slide 7 of 107

My Birthday Wish:

twitch.tv/verolafox | twitter.com/hufflepuffcodes

twitch.tv/mayanwolfe | twitter.com/mayanwolfe

twitch.tv/helloitsrufio | twitter.com/helloitsrufio

self-taught

community-taught


Slide 8 of 107

Fresh Start


Slide 9 of 107

Networking

Alternatives?

1 coffee chat this week


Slide 10 of 107

USE THE SHEET!

NOW WITH TWO TABS!: Google Sheet


Slide 11 of 107

Grab The Checklist

!checklist


Slide 12 of 107

PUSH EVERY DAY


Slide 13 of 107

Submitting Work

Freelancing Submission

 


Slide 14 of 107

Submitting Work

Checklist, 100Hours Project, Codewars

 


Slide 15 of 107

Spaced Repetition

Ali Abdaal: https://youtu.be/Z-zNHHpXoMM


Slide 16 of 107

Backend!

Butt first!


Slide 17 of 107

Let's Deliver Some Papers


Slide 18 of 107

Synchronous

Waiting for them to come to the door


Slide 19 of 107

Asynchronous

Moving onto the next house


Slide 20 of 107

Javascript is

single-threaded

Synchronous aka processes

one operation at a time

 

vs


Slide 21 of 107

If synchronous, how do we do stuff like make an api request and keep scrolling or clicking


Slide 22 of 107

Things should block


Slide 23 of 107

THE ENVIRONMENT


Slide 24 of 107

Not This


Slide 25 of 107

THIS


Slide 26 of 107

Our JS is running in

a browser

 

Browsers have a BUNCH of APIs we can use that are async and enable us to keeping looking a cute cat photos while those operations are being processed asynchronously


Slide 27 of 107

Common browser APIs

 DOM (Document Object Model) API


Slide 28 of 107

*the DOM (Document Object Model) is essentially the API one uses to manipulate an HTML (or XML) document -- usually using JavaScript

*stackoverflow from 10 years ago...


Slide 29 of 107

! USUALLY !


Slide 30 of 107

WAIT
WHAT THE FUCK

Actual words Leon said when figuring all this shit out...


Slide 31 of 107

Slide 32 of 107

So, yeah, JS can do a lot of "blocking" stuff in the browser because it is handing that stuff off to async

Web APIs


Slide 33 of 107

BUT

We are going to need to know how to handle responses coming back from those Web APIs

 

JS does this with callbacks, promises,

and eventually async/await


Slide 34 of 107

Call stack, Call Back Queue, Web API, Event Loop

Tuesday


Slide 35 of 107

Let's Deliver Some Papers


Slide 36 of 107
function houseOne(){
    console.log('Paper delivered to house 1')
}
function houseTwo(){
    console.log('Paper delivered to house 2')
}
function houseThree(){
    console.log('Paper delivered to house 3')
}

houseOne()
houseTwo()
houseThree()

Slide 37 of 107

Let's Use A Web API 

setTimeout()


Slide 38 of 107

setTimeout and setInterval are not part of the Javascript specification...

 

Most environments include them...

like all browsers and Node.js


Slide 39 of 107

Live Leon Footage


Slide 40 of 107
function houseOne(){
    console.log('Paper delivered to house 1')
}
function houseTwo(){
    setTimeout(() => console.log('Paper delivered to house 2'), 3000)
}
function houseThree(){
    console.log('Paper delivered to house 3')
}
houseOne()
houseTwo()
houseThree()

Slide 41 of 107
function houseOne(){
    console.log('Paper delivered to house 1')
}
function houseTwo(){
    setTimeout(() => console.log('Paper delivered to house 2'), 0)
}
function houseThree(){
    console.log('Paper delivered to house 3')
}
houseOne()
houseTwo()
houseThree()

Slide 42 of 107

EVENT LOOP

Thursday


Slide 43 of 107

What if it is pay day?


Slide 44 of 107

I only want to move onto the third house after the second house has paid me

Real world this would be getting data back from an API ect...


Slide 45 of 107

The Old School Way

Callbacks


Slide 46 of 107

You can have a function that takes another function as an argument

aka Higher Order Function


Slide 47 of 107

You have seen this a million times

addEventListener('click', callback)


Slide 48 of 107

A Callback is the function that has been passed as an argument

Callbacks are not really "a thing" in JS

just a convention 


Slide 49 of 107

Let's Get Paid


Slide 50 of 107
function houseOne(){
    console.log('Paper delivered to house 1')
}
function houseTwo(callback){
    setTimeout(() => {
        console.log('Paper delivered to house 2')
        callback()
    }, 3000)
}
function houseThree(){
    console.log('Paper delivered to house 3')
}

houseOne()
houseTwo(houseThree)

Slide 51 of 107

Callback fires when async task or another function

 is done


Slide 52 of 107

Let's Get Paid By Everyone


Slide 53 of 107
function houseOne(){
    setTimeout(() => {
        console.log('Paper delivered to house 1')
        setTimeout(() => {
            console.log('Paper delivered to house 2')
            setTimeout(() => {
                console.log('Paper delivered to house 3')
            }, 3000)
        }, 4000)
    }, 5000)
}
houseOne()

Slide 54 of 107

Welcome To Hell

Callback Hell


Slide 55 of 107

What if there was a more readable way to handle async code


Slide 56 of 107

Promise


Slide 57 of 107

A promise is an object that represents the eventual completion or failure of an async operation and its value


Slide 58 of 107

An object that MAY have a value in

the future


Slide 59 of 107

A promise can have three possible states

 


Slide 60 of 107

.then()

A promise object method that runs after the promise "resolves"

 


Slide 61 of 107

.then(value)

Whatever value the promise object has gets passed as an argument

 


Slide 62 of 107

We've Seen This Before


Slide 63 of 107

APIs

Fetch Fido, Fetch!

fetch("https://dog.ceo/api/breeds/image/random")
    .then(res => res.json()) // parse response as JSON
    .then(data => {
      console.log(data)
    })
    .catch(err => {
        console.log(`error ${err}`)
    });

API returns a JSON object that we can use within our apps


Slide 64 of 107

Fetch returns a Promise

Like a bunch of Web APIs running async code


Slide 65 of 107

Let's see those

three states


Slide 66 of 107
const promise = new Promise((resolve, reject) => {
    const error = false
    if(!error){
        resolve('Promise has been fullfilled')
    }else{
        reject('Error: Operation has failed')
    }
})
console.log(promise)
promise
    .then(data => console.log(data))
    .catch(err => console.log(err))

Slide 67 of 107

Let's Get Paid By Everyone


Slide 68 of 107
function houseOne(){
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Paper delivered to house 1')
        }, 1000)
    })
}
function houseTwo(){
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Paper delivered to house 2')
        }, 5000)
    })
}
function houseThree(){
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Paper delivered to house 3')
        }, 2000)
    })
}
houseOne()
    .then(data => console.log(data))
    .then(houseTwo)
    .then(data => console.log(data))
    .then(houseThree)
    .then(data => console.log(data))
    .catch(err => console.log(err))

Slide 69 of 107

Chaining Don't Read Good


Slide 70 of 107

I want my asynchronous code to look sychronous


Slide 71 of 107

Async / Await


Slide 72 of 107

A way to handle async responses


Slide 73 of 107

Promises Under The Hood

Syntactic sugar on top of promises, making asynchronous code easier to write and to read afterwards


Slide 74 of 107

Await waits for an async process to complete inside an Async Function


Slide 75 of 107
function houseOne(){
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Paper delivered to house 1')
        }, 1000)
    })
}
function houseTwo(){
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Paper delivered to house 2')
        }, 5000)
    })
}
function houseThree(){
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Paper delivered to house 3')
        }, 2000)
    })
}
async function getPaid(){
    const houseOneWait = await houseOne()
    const houseTwoWait = await houseTwo()
    const houseThreeWait = await houseThree()
    console.log(houseOneWait)
    console.log(houseTwoWait)
    console.log(houseThreeWait)
}
getPaid()

Slide 76 of 107
async function getPaid(){
    const houseOneWait = await houseOne()
    const houseTwoWait = await houseTwo()
    const houseThreeWait = await houseThree()
    console.log(houseOneWait)
    console.log(houseTwoWait)
    console.log(houseThreeWait)
}
getPaid()

Slide 77 of 107

I Need Something Real


Slide 78 of 107

Let's Code

An API request using Async/Await


Slide 79 of 107

APIs

Fetch Fido, Fetch!

async function getACuteDogPhoto(){
    const res = await fetch('https://dog.ceo/api/breeds/image/random')
    const data = await res.json()
    console.log(data)
}
getACuteDogPhoto()

Slide 80 of 107

Backend BABY


Slide 81 of 107

Does Javascript have access to the DOM natively (built in)?


Slide 82 of 107

Slide 83 of 107

Javascript needed Web APIs to handle async and a bunch of stuff in the Browser 


Slide 84 of 107

JS is sandboxed

in the browser


Slide 85 of 107

JS is a language that can only do what the hosting environment allows


Slide 86 of 107

What Do Servers Need?


Slide 87 of 107

Disk Access

(hardrive/ssd)

&&

Network Access

(internet, request / responses)


Slide 88 of 107

What if there was a hosting environment that allowed JS to have disk and network access

Music & Light Warning - Next Slide


Slide 89 of 107

NODE.js BABY


Slide 90 of 107

Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine.


Slide 91 of 107

Slide 92 of 107

The same shit that lets you run JS in the browser can now be used to run JS on Servers, Desktops, and elsewhere


Slide 93 of 107

True Story

V8 Engine Does All The Heavy Lifting


Slide 94 of 107

And just like the browser's Web APIs Node come with a bunch of stuff


Slide 95 of 107

Built in Modules

(libraries or collections of functions)

 

HTTP (network access)

FS (file system access)


Slide 96 of 107

Access to millions of packages via NPM

(groupings of one or more custom modules)


Slide 97 of 107

sorry, don't remember the source


Slide 98 of 107

Call stack, Call Back Queue, Node Modules, Event Loop

Tuesday


Slide 99 of 107

Install Node


Slide 100 of 107

Releases?

LTS, Current, Nightly?


Slide 101 of 107

Let's Code

Simple Node Server


Slide 102 of 107

Just

HTTP & FS

const http = require('http')
const fs = require('fs')
http.createServer((req, res) => {
  fs.readFile('demofile.html', (err, data) => {
    res.writeHead(200, {'Content-Type': 'text/html'})
    res.write(data)
    res.end()
  })
}).listen(8000)

Music & Light Warning - Next Slide


Slide 103 of 107

You are now a

Software Engineer

that can build

Fullstack Web Applications


Slide 104 of 107

Let's Look

More Complex Backend


Slide 105 of 107

Slide 106 of 107

How could we clean this up?


Slide 107 of 107

Homework

 

Do: Start prepping THE BANK

Do: Complete Your Professional Links

Do: Make node-backend-simple-json more readable

Do: Make a coinflip game where the randomization happens server side