Skip to content

vicompany/workshop-async-await

Repository files navigation

Workshop Async/await

This repository contains a mock server, dummy code and documentation to acquire knowledge of async functions.

The basics aka the golden rules of async/await

ES7 Async/await allows us to write asynchronous JavaScript code that looks synchronous.

1. The foundation of async functions are Promises.

So readup on Promises when you don't fully understand them yet.

2. Async functions always return a Promise when called

async function greet(name) {
  if (name.toLocaleLowerCase() === 'bob'){
    throw new Error('Not allowed');
  }

  return `Hello ${name}`;
}

greet('Joe')
  .then(console.log) // Hello Joe

greet('Bob')
  .then(console.log)
  .catch(console.error); // Error: Not allowed

3. An async function can contain an await expression

  • The await operator is used to wait for the result of a Promise.
  • The await operator can only be used inside an async function!
const getJson = url => fetch(url).then(res => res.json());

const getUsers = async () => {
  const users = await getJson('/users');

  console.log(users);
}

getUsers();

When the return value of the await expression is not a Promise, it's converted to a resolved Promise.

async function w00t() {
  const value = await 1337;

  console.log(value); // 1337
}

w00t();

And when the return value is a Promise, you can just return it without using await (and without wrapping the result).

async function getStuff(id) {
  const url = await getUrl(id);

  return fetch(url).then(res => res.json());
}

// Don't do this!
async function getStuff(id) {
  const url = await getUrl(id);

  return await fetch(url).then(res => res.json());
}

4. Handling errors and results with await.

The operator await waits for its operand, a Promise, to be settled:

  • If the Promise is fulfilled, the result of await is the fulfillment value.
  • If the Promise is rejected, await throws the rejection value.
async function getUsers() {
  let users = [];

  try {
    users = await getJson('/users');
  } catch (err) {
    console.error(`Could not retrieve users: ${err.message}`);
  }

  return users;
}

5. await is sequential, use Promise.all() for parallel execution

The following functions are executed sequentially.

async function foo() {
  const result1 = await asyncFunc1();
  const result2 = await asyncFunc2();
}

But executing them in parallel can speed things up. And you can use ES6 destructuring assignment.

async function foo() {
  const [result1, result2] = await Promise.all([
    asyncFunc1(),
    asyncFunc2(),
  ]);
}

More information

Getting started

Assignment

The demo project contains some nice callback-based JavaScript code which uses the Github REST API to display information about our repositories.

It's up to you to:

  • Rewrite this code to async/await (remove the callbacks and add some functions).
  • Add the sum of the contributions.
  • Add the user details.
  • Go crazy if you like. 🤘

Notes

  • You need the latest Chrome or Firefox browser for this to run.
  • A cache (localStorage) is used to circumvent the APIs rate limiting. So keep that in place.
  • For Firefox you need to enable the following settings (in about:config):
    • ES Modules: dom.moduleScripts.enabled.
    • The <dialog> element: dom.dialog_element.enabled.

About

An ES2017 async/await workshop using the github API

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published