Skip to content

Instantly share code, notes, and snippets.

@ivankisyov
Last active October 14, 2018 15:00
Show Gist options
  • Save ivankisyov/36208a607bd36580fe535f17dcd064d2 to your computer and use it in GitHub Desktop.
Save ivankisyov/36208a607bd36580fe535f17dcd064d2 to your computer and use it in GitHub Desktop.
Async Await

Async Await {Node.js}

if a function returns a promise, you can AWAIT the result of that promise!

const axios = require("axios");

const getCountry = async countryCode => {
  try {
    const response = await axios.get(
      `https://restcountries.eu/rest/v2/currency/${countryCode}`
    );
    return response.data[0].name;
  } catch (error) {
    throw new Error("country code does not exist");
  }
};

const getFlag = async capital => {
  try {
    const response = await axios.get(
      `https://restcountries.eu/rest/v2/capital/${capital}`
    );
    return response.data[0].flag;
  } catch (error) {
    throw new Error("no such capital");
  }
};

const getInfo = async (countryCode, capital) => {
  const country = await getCountry(countryCode);
  const flag = await getFlag(capital);
  return {
    info: {
      country,
      flag
    }
  };
};

getInfo("bgn", "sofia")
  .then(info => {
    console.log(info);
  })
  .catch(err => {
    console.log(err);
  });

Destructuring assignment

const axios = require("axios");

async function displayInfo() {
  // get album
  const { data: album } = await axios.get(
    "https://jsonplaceholder.typicode.com/albums/11"
  );
  // get todo
  const { data: todo } = await axios.get(
    "https://jsonplaceholder.typicode.com/todos/3"
  );
  // get user
  const { data: user } = await axios.get(
    "https://jsonplaceholder.typicode.com/users/4"
  );
  let info = {
    todo,
    user,
    album
  };
  console.log(info);
}

displayInfo();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment