Session Plan

Session Materials

These are some examples of previously created materials by mentors that you can use yourself, or for inspiration.

Session Outline

Promises is notoriously difficult to teach! I teach consumption and creation of promises totally separate! And show them that it's just like with functions. There is a creation part and a consumption part.

First when they fully understand one part of promises, I move on! Don't over-complicate things. Only mention the resolve function to begin with. When they get that, say that there also is a reject function. Take as many baby steps as is possible! Don't mention that resolve and reject can take an argument to begin with, first later explain that.

Exercises

Exercise 1

Using async await

  1. fetch yes or no from this api: https://yesno.wtf/api. log out the answer

Exercise 2

Using promises

  1. fetch yes or no from this api: https://yesno.wtf/api. log out the answer

  2. Try fetching a url that rejects e.g. https://knajskdskj.jasdk. Log out the error message

Exercise 3

  1. Create a promise that resolves after 4 seconds. Use this promise to log out the text 'hello' after 4 seconds.

  2. Now make the promise fail by rejecting it with an error message instead of resolving it, and log the error message to the console.

Exercise 4

Create a function that returns a promise, that you can use like this:

The above example show how to consume the promise using promises. Now try consume the YesNoFail4Seconds using async/await

Exercise 5

Using async await

  1. Fetch the astronauts

  2. After the astronauts has been fetched, fetch movies using this api

  3. Log out the movies

Exercise 6

Get the astronauts and the movies at the same time. Log out the movies and the battery status when both promises has been resolved.

Code inspiration

Async/await - simple usage

Promise consumption

So how did the async/await example above actually work? Let's get into promises!

If you have a promise, you can call two functions on that promise. '.then' and '.catch'. When are these functions called? What does it mean that a promise is resolved or rejected?

The trainees should be able to answer these questions: // Question 1: What does it mean that a promise is resolved? Which method on a promise get called? // Question 2: What does it mean that a promise is rejected? Which method on a promise get called? // How would you explain your mom what resolved and rejected means?

Promise creation

When you create a new promise you give it a function that has two functions as parameters (resolve and reject). Resolve is called when everything in a promise goes well. Reject is called when something goes wrong.

Back to async/await

So writing async in front of a function makes it return a promise! The keyword await makes JavaScript wait until that promise resolved and returns its result.

Function that returns a promise

Last updated