SpaceComp
An end to our intermediate JS
Today
Why
Table of Contents
- Why.
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
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.
A Touch of Promises
Table of Contents
- One Example
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.
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.
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).
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.
Promises
Table of Contents
- Making Promises
- Keeping Promises
- Breaking Promises
- Promise Inception
Async function Making Promises
async function eotStatus() {
return “cancelled”;
}
eotStatus();
-> Promise returned
We can modify functions to be asynchronous.
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”.
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.
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!
The Last Keyword
Table of Contents
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.
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.
Next Time
And of course thanks for coming. I hope you all had fun and learned a lot. :)