ES8 async await

Async await is part of ES8 and is built on top of promises.

Async function is a function that returns a promise, but the benefit of async await is that makes code easier to read. A promise in JavaScript is that promise to return something to you in the future. For example, from database or APIs calls. These requests take time.

Default async vs ES8 async await

const fetch = require("node-fetch");

const fetchUserByDefault = function () {
  fetch("https://jsonplaceholder.typicode.com/users")
    .then((res) => res.json())
    .then(function (data) {
      console.log("Default Aysnc way");
      console.log(data[data.length - 1].id);
    });
};

const fetchUsersByAsync = async function () {
  const res = await fetch("https://jsonplaceholder.typicode.com/users");
  const data = await res.json();
  console.log("ES8 Async Function way");
  console.log(data[data.length - 1].id);
};

fetchUserByDefault();
fetchUsersByAsync();
Default Aysnc way
10
ES8 Async Function way
10

Promise.all and try and catch

cconst fetch = require("node-fetch");

const urls = [
  "https://jsonplaceholder.typicode.com/users",
  "https://jsonplaceholder.typicode.com/posts",
];

const allDataFromUrls = async function () {
  try {
    const [users, posts] = await Promise.all(
      urls.map((url) => fetch(url).then((res) => res.json()))
    );
    console.log(users[users.length - 1].id);
    console.log(posts[posts.length - 1].id);
  } catch (err) {
    console.log("error: " + err);
  }
};

allDataFromUrls();
10
100

Leave a Reply

Your email address will not be published.

ANOTE.DEV