Asynchronous Programming

Slide navigation: Forward with space bar, , or PgDn. Backwards with or PgUp.

Example: Loading an Image

Demo

images.html

Asynchronous Programming

Promises

The Promise Concept

Example: Loading an Image

function loadImage(url) {
  return new Promise((resolve, reject) => {
    const callback = () => {
      try {
        const response = request.response
        const blob = new Blob([response], {type: 'image/png'})
        const img = document.createElement('img')
        img.src = window.URL.createObjectURL(blob)
        resolve(img)
      } catch (e) {
        reject(e)
      }
    }

    const request = new XMLHttpRequest()
    request.open('GET', url)
    request.responseType = 'blob'
    request.addEventListener('load', callback)
    request.send()
  })  
}

Example: Producing a Value after a Delay

function produceAfterDelay(what, when) {
  return new Promise((resolve, reject) => {
    const callback = () => resolve(what)
    setTimeout(callback, when)
  })                     
}

Promise Control Flow

Obtaining Promise Results

Working with Promises

Promise Chaining

Demo

images2.html

Demo

function produceAfterDelay(what, when) {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(what), when)
  })                     
}

const promise2 = produceAfterDelay(42, 3000)
promise2.then(console.log)

Cleaning Up Promise Chaining

More Promise Chaining

Demo

images3.html

Fetch API

fetch('https://aws.random.cat/meow')
  .then(result => result.json()) // Asynchronous
  .then(console.log)
    // An object such as { file: 'https://purr.objects-us-east-1.dream.io/i/pBo0r.jpg'}

Rejection Handling

Catch

Finally

Immediately Settled Promises

Executing Multiple Promises

Demo all and race with images

images5.html

Async and Await

Async Functions

Await

Async Syntax

Multiple Awaits

Concurrent Await

Async Return Values

Exceptions in Async Functions

Async Iterators and Generators

Async Iterators and Generators

The for await of Loop

async range

timedrange.js

End of Lesson 10