Async/await example I.

Made for kutac.cz/blog

HTML

<p id="i"></p>

Babel + JSX

const print = (s) => document.querySelector("#i").innerHTML += `${s}<br>`

function printAuthor(postId) {
	fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`)
    .then(res => res.json())
    .then(post => fetch(`https://jsonplaceholder.typicode.com/users/${post.userId}`))
    .then(res => res.json())
    .then(user => print(`Promise: ${user.name}`))
    .catch(error => print(error))
}

printAuthor(42)

async function printAuthorAsync(postId) {
  try {
    let res = await fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`)
    const post = await res.json()
    res = await fetch(`https://jsonplaceholder.typicode.com/users/${post.userId}`)
    const user = await res.json()
    print(`Async / await: ${user.name}`)
  }
  catch (error) {
  	print(error)
  }
}

printAuthorAsync(42)