1 of 19

SpaceComp

An end to our intermediate JS

2 of 19

Today

  • Asynchronous programming
    • Coding outside the bounds of time itself

3 of 19

Why

Table of Contents

- Why.

4 of 19

Why

All the code we’ve written is “blocking”.

Nothing else runs while one line of code is running.

E.g. If a function is running nothing else can either.

What if you download a file?

-> The program freezes

What if you make a multiplayer game and you’re waiting for the other person’s action.

-> The program still freezes

5 of 19

Why 2.0

Instead of blocking code we can write asynchronous code.

“When my (async) function finishes returning a value (promise) run this code (everything else). In the meantime skip it.”

How will it work?

Your computer will repeatedly check if the async function has finished and if so it will run it. Otherwise it’ll keep doing something else.

6 of 19

A Touch of Promises

Table of Contents

- One Example

7 of 19

A Mozilla Example

fetch('products.json').then(function(response) {

return response.json();

}).catch(function(err) {

console.log('Fetch problem: ' + err.message);

});

fetch(‘products.json’) will download a file and return the data. But it might take a while.

Let’s simplify with arrow syntax first.

8 of 19

A Mozilla Example - Arrowed Edition

fetch('products.json').then(response => response.json()).catch(err => {

console.log('Fetch problem: ' + err.message);

});

We can move the .then and .catch to their own lines so let’s do that too.

9 of 19

A Mozilla Example - Clean Arrowed Edition

fetch('products.json')

.then(response => response.json())

.catch(err => {

console.log('Fetch problem: ' + err.message);

});

Fetch might take a while.

It returns one value.

Inside then we define a function that takes this one value and runs some code.

Inside catch we define a function that runs if an exception is raised. It takes in err, much like try, catch(err).

10 of 19

Reviewing the Example

Most functions won’t let us use .then and .catch.

Async functions return a special value called a promise. A promise contains a status (pending, finished with value, errored with error value).

We can use .then and .catch to define what we do when the promise isn’t pending.

This example was complicated. Let’s start simpler.

11 of 19

Promises

Table of Contents

- Making Promises

- Keeping Promises

- Breaking Promises

- Promise Inception

12 of 19

Async function Making Promises

async function eotStatus() {

return “cancelled”;

}

eotStatus();

-> Promise returned

We can modify functions to be asynchronous.

13 of 19

Keeping Promises

> eotStatus().then(result => console.log(result));

Promise { <pending> }

> cancelled

We got a promise as we waited for eotStatus result.

Then we ran the .then and printed “cancelled”.

14 of 19

Breaking Promises

async function eot(){

throw “covid-19 cancellation”;

return “having fun”;

}

eot()

.then(msg => console.log(msg))

.catch(err => console.log(err));

> eot().then(msg => console.log(msg)).catch(err => console.log(err));

Promise { <pending> }

> covid-19 cancellation

The .catch ran because we got an exception. Remember throw from Lesson 3.

15 of 19

Promise Inception

async function today(){

return “studying”;

}

today() // Return a promise with “studying”

.then(msg => msg + “, healthy”) // Promise with new string

.then(msg => msg + “, happy”) // Promise another new string

.then(msg => console.log(msg)); // Empty promise

> Promise { <pending> }

> studying, healthy, happy

We can chain our promises.

When a .then returns a value that value is itself a promise.

We then attach a .then to our .then

And we just keep going!

16 of 19

The Last Keyword

Table of Contents

  • await

17 of 19

await

How do we store the result of a promise rather than using it inside a .then?

We use await to make things act a little more synchronous again.

Unfortunately it only works inside async functions.

We will rewrite our old example using await.

18 of 19

The Final Example

async omegaExample () {

let first = today();

console.log(first);

}

omegaExample();

-> studying

async function today(){

return “studying”;

}

We have taken the value from a promise by waiting for it to finish before moving back to where we started calling.

19 of 19

Next Time

  • You can submit your bots on Slack!
  • Keep an eye out for a video showing the competition.
  • Don’t get COVID-19
  • Maybe see you next winter
  • Good luck with exams

And of course thanks for coming. I hope you all had fun and learned a lot. :)