Skip to content

Latest commit

 

History

History
232 lines (184 loc) · 8.89 KB

File metadata and controls

232 lines (184 loc) · 8.89 KB

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

See Exercises. Trainees show results on the page (update the DOM), not in the console.

Console order – Optional “what is logged?” promise chaining.

Code inspiration

Async/await - simple usage

// Warm up exercise. The trainees has to say everything they can about a variable, ONLY from the variable name. e.g. the type, what it returns, what object we could expect etc.
// cars, car, title, getTitle, addTitle, isTitle, hasTitle, hasItem, users, year, yearIndex, user, review.
// DON'T EXPLAIN WHAT ASYNC OR AWAIT DOES YET! Explain on a higher level:
// You have to write async before a function for await to work. No details for now
// await waits until we have fetched the data from the api. Or said in another way await waits until fetch has resolved with the data from the api

// write async before a function for await to work. What does it mean that something is asynchronous?
// JSONPlaceholder works reliably in the browser (same idea as Open Notify / astronauts, different URL).
async function getJsonPlaceholderUser() {
  // await waits until we have data from fetch before it runs the next line. No need for callbacks 🤯
  console.log("Before we fetch data");
  const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
  console.log(
    "This is logged out after some time, even though the code looks synchronous! 🤯",
  );
  const user = await response.json();
  console.log("This is logged out after some time! 🤯");
  console.log(user);
  return user;
}

getJsonPlaceholderUser();

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?

fetch("https://jsonplaceholder.typicode.com/users/1")
  .then((response) => response.json())
  .then((user) => {
    console.log(user);
  })
  .catch((error) => console.log(error));

// https://codesandbox.io/s/scrollto-promise-example-0gjp6
// If not working try chrome
scrollTo("section.features")
  .then(() => console.log("scrolling done"))
  .catch((error) => console.log(error));

// HAMMER in this point:
// When you have a promise you can call two functions on that promise (.then and .catch). '.then' is called when the promise is resolved. '.catch' is called when the promise is rejected.

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.

// Start as simple as possible, no reject, just resolve!
const oneSecondTimeoutPromise = new Promise((resolve) => {
  setTimeout(() => {
    resolve();
  }, 1000);
});

// You can pass data in the resolve
const oneSecondTimeoutPromise = new Promise((resolve) => {
  setTimeout(() => {
    resolve("1 second has passed");
  }, 1000);
});

oneSecondTimeoutPromise.then((timeoutData) => {
  console.log(timeoutData); // '1 second has passed'
});

const orderPizzaPromise = new Promise((resolve, reject) => {
  const pizzaMakingTime = 10000;
  const didPizzaBakingSucceed = true;
  const pizza = "Macaroni pizza";
  setTimeout(() => {
    if (didPizzaBakingSucceed) {
      resolve(pizza);
    } else {
      reject("The pizza was a mess");
    }
  }, pizzaMakingTime);
});

orderPizzaPromise
  .then((pizza) => {
    console.log(`Let's eat the ${pizza}`);
  })
  .catch((error) => {
    console.log(`Let's eat the nothing`);
  });

// HAMMER in this point:
// 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.

// Compare function creation and consumption to promise creation and consumption
// function creation
function test() {}

// function usage
console.log(test());

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.

async function getJsonPlaceholderUserSafe() {
  try {
    const response = await fetch(
      "https://jsonplaceholder.typicode.com/users/1",
    );
    const user = await response.json();
    return user;
  } catch (err) {
    throw "Fetching the user went wrong";
  }
}

const userPromise = getJsonPlaceholderUserSafe();

Function that returns a promise

// This example could definitely be more real world! Any ideas, make a pull request!
const promise = new Promise((resolve) => {
  setTimeout(() => {
    const tea = {
      color: "green",
      taste: "Bitter",
    };

    resolve(tea);
  }, 3000);
});

const isThereMoreTea = false;

// This example could definitely be more real world! Any ideas, make a pull request!
function makeTea() {
  console.log("Start making tea");

  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const tea = {
        color: "green",
        taste: "Bitter",
      };

      if (isThereMoreTea) {
        resolve(tea);
      } else {
        reject("We don't have more TEA!!");
      }
    }, 3000);
  });
}

console.log(makeTea());

makeTea()
  .then((returnedTeaObject) => {
    console.log(returnedTeaObject);
  })
  .catch((error) => {
    console.log(error);
  });