Async/Await  - Practice on  Asyn JS using  Github API

Async/Await - Practice on Asyn JS using Github API

Today we will explore how to use Async/Await for asynchronous javascript through GitHub API.

Example #1

Use of await - Await keyword will stop the execution of JS code unless Promise is settled with a resolved value or rejected error.

import fetch from "node-fetch";

// function getGithhubUserName(handler) {
//   const url = `https://api.github.com/users/${handler}`;
//   fetch(url)
//     .then((res) => res.json())
//     .then((user) => {
//       console.log(user.name);
//       console.log(user.location);
//     });
// }

//convert to Async function
async function getGithhubUserName(handler) {
  const url = `https://api.github.com/users/${handler}`;
  const res = await fetch(url);
  const user = await res.json();
  //   console.log(user.name);
  //   console.log(user.location);
  return user;
}

// getGithhubUserName("vijendra-tech").then((user) => {
//   console.log(user.name);
//   console.log(user.location);
// });

//in latets verison of node >16, await can be used without async function
const user = await getGithhubUserName("vijendra-tech");
console.log(user.name);
console.log(user.location);

Example #2 - with class

import fetch from "node-fetch";

class GitHubApiLClient {
  async getUser(handler) {
    const url = `https://api.github.com/users/${handler}`;
    const res = await fetch(url);
    const user = await res.json();
    return user;
  }
}

const client = new GitHubApiLClient();
const user = await client.getUser("vijendra-tech");
console.log(user.name);
console.log(user.location);

Example #3 - Handling Error

import fetch from "node-fetch";

async function getGithhubUserName(handler) {
  const url = `https://api.github.com/users/${handler}`;
  const res = await fetch(url);
  const body = await res.json();
  if (res.status !== 200) {
    throw Error(body.message);
  }
  return body;
}

// const user = await getGithhubUserName("vijendra-tech-01").catch((err) => {
//   console.log(`Error: ${err.message}`);
// });
// console.log(user);
// // console.log(user.location);

//wrap in try catch
async function showUser(handle) {
  try {
    const user = await getGithhubUserName(handle);
    console.log(user.name);
    console.log(user.location);
  } catch (error) {
    console.log(`Error: ${error.message}`);
  }
}

showUser("vijendra-tech-1");

Example #4 - When using more than one await keyword, it means we try to do the synchronous operation. To make it parallel.

import fetch from "node-fetch";

async function fetchDetailsFromGithub(endpoint) {
  const url = `https://api.github.com${endpoint}`;
  const response = await fetch(url);
  return response.json();
}

async function showUserAndRepo(handle) {
  // these calls are sequential calls
  //   const user = await fetchDetailsFromGithub(`/users/${handle}`);
  //   const repos = await fetchDetailsFromGithub(`/users/${handle}/repos`);

  //to make parallel
  //   const userPromise = fetchDetailsFromGithub(`/users/${handle}`);
  //   const reposPromise = fetchDetailsFromGithub(`/users/${handle}/repos`);
  //   const user = await userPromise;
  //   const repos = await reposPromise;

  //Or other option by using promise.all() - better readibility
  const [user, repos] = await Promise.all([
    fetchDetailsFromGithub(`/users/${handle}`),
    fetchDetailsFromGithub(`/users/${handle}/repos`),
  ]);

  console.log(user.name);
  console.log(`${repos.length} repos`);
}

showUserAndRepo("vijendra-tech");

Example # 5 - using await keyword with nonpromise then it will implicitly convert to Promise with resolved value.

async function main() {
  // it is converting implicit Promise.resolve(90)
  const z = await 90;

  console.log(z);
}

main();

Full codes are available on GitHub.

Or Open codes in the new Tab.

Happy Coding :)

Did you find this article valuable?

Support Vijendra Rana by becoming a sponsor. Any amount is appreciated!