ASYNC AWAIT

by 1eddy87

HTML

<div id="test">Loading</div>

JavaScript

/* ASYNC AWAIT */

const posts = [{
    title: 'post one',
    body: 'this is post one'
  },
  {
    title: 'post two',
    body: 'this is post two'
  }
]

function getPosts() {
  setTimeout(() => {
    let output = '';
    posts.forEach((post) => {
      output += `<div>${post.title}</div>`;
    });

    document.getElementById('test').innerHTML = output;
  }, 1000);
}

function createPost(post) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      posts.push(post);

      const error = false;

      if (!error) {
        resolve();
      } else {
        reject('Error: something went wrong.');
        document.getElementById('test').innerHTML = 'Error: something went wrong.';
      }
    }, 2000);
  });
}

// async / await
/* 
async function init() {
  await createPost({
    title: 'post three',
    body: 'this is post three'
  });
  
  getPosts();
}

init();
*/

// async / await / fetch
async function fetchUsers() {
  const res = await fetch('https://jsonplaceholder.typicode.com/users');
  const data = await res.json();

  console.log(data);
  document.getElementById('test').innerHTML = JSON.stringify(data, null, 2);
}

fetchUsers();

/* ASYNC AWAIT */