Asynchronous JavaScript

Problem

In the below-given example we can see that, we are calling getPost() function before and after createPost() function still “Post Three” is not loading. That’s because, getPost gets executed in 1s and createPost is called after 2s, after the DOM is painted.

image

Solution

Posts Object

const posts = [
  {
    title: "Post One",
    body: "Lorem ipsum, dolor sit amet consectetur adipisicing elit.",
  },
  {
    title: "Post Two",
    body: "Lorem ipsum, dolor sit amet consectetur adipisicing elit.",
  },
];

1. Using Callback

function getPosts() {
  setTimeout(() => {
    let output = "";
    posts.map((post) => {
      output += `<h1>${post.title}</h1> ${post.body}\n`;
    });
    document.body.innerHTML = output;
  }, 1000);
}
 
function createPost(post, callback) {
  setTimeout(() => {
    posts.push(post);
    callback();
  }, 2000);
}
 
createPost(
  {
    title: "Post Three",
    body: "Lorem ipsum, dolor sit amet consectetur adipisicing elit. Qui nisi dicta eligendi velit unde tempora modi quod ratione suscipit! Laboriosam.",
  },
  getPosts
);

image

2. Using Promise

function getPosts() {
  setTimeout(() => {
    let output = "";
    posts.map((post) => {
      output += `<h1>${post.title}</h1> ${post.body}\n`;
    });
    document.body.innerHTML = output;
  }, 1000);
}
 
function createPost(post) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      posts.push(post);
      let error = true;
      if (error) reject("Error: Something went wrong");
      else resolve();
    }, 2000);
  });
}
 
createPost({
  title: "Post Three",
  body: "Lorem ipsum, dolor sit amet consectetur adipisicing elit. Qui nisi dicta eligendi velit unde tempora modi quod ratione suscipit! Laboriosam.",
}).then(getPosts);

image image

3. Using Async / Await

function getPosts() {
  setTimeout(() => {
    let output = "";
    posts.map((post) => {
      output += `<h1>${post.title}</h1> ${post.body}\n`;
    });
    document.body.innerHTML = output;
  }, 1000);
}
 
function createPost(post) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      posts.push(post);
      let error = false;
      if (error) reject("Error: Something went wrong");
      else resolve();
    }, 2000);
  });
}
 
async function init() {
  // It will wait until createPost is completely executed
  await createPost({
    title: "Post Three",
    body: "Lorem ipsum, dolor sit amet consectetur adipisicing elit",
  });
  getPosts();
}
 
init();

image

Fetch API using async await

const API = "https://jsonplaceholder.typicode.com/users";
async function getUser() {
  const res = await fetch(API);
  const data = await res.json();
  console.log(data);
}
 
getUser();

image