How To Master Async/Await With This Real World Example Asynchronous methods in ES6 have become an integral part of development and this article is a quick way to learn how to use Async/Await in real development

directory

  1. Introduction (callbacks, promise, async/await)
  2. Real world example – currency converter that receives asynchronous data from two apis

Before we get into the text

I created a YouTube video while writing this! You can write code while you’re watching. I encourage you to read this article and then code along with the video.

Learn Async/Await in This Real World Project

introduce

Async/Await is a new way to write asynchronous code. It builds on promise, so it’s also non-blocking.

The big difference is that the use of Async/Await makes asynchronous code look a bit like synchronous code. That is all its power. Asynchronous code used to have a choice between callbacks and promises.

Use of the callbacks function

setTimeout(() => {
  console.log('This runs after 1000 milliseconds.');
}, 1000);
Copy the code

Problems with callbacks – callback hell

Nested callback functions within callback functions will soon look like this:

Callbacks are nested several layers deep within other callbacks, which can make it difficult to understand and maintain code.

The use of the promise

const promiseFunction = new Promise((resolve, reject) => {
  const add = (a, b) => a + b;
  resolve(add(2, 2));
});
promiseFunction.then((response) => {
  console.log(response);
}).catch((error) => {
  console.log(error);
});
Copy the code

The promiseFunction returns a Promise representing the procedure of the function. The resolve function signals to the Promise instance that it is complete.

Then we can call the then() and catch() functions in the promise function:

  1. Then – The callback passed to run the Promise function when it completes
  2. Catch – The callback passed to the Promise function when it runs in error

Async function

Async functions give us a clean, concise syntax that allows us to write less code to achieve the same results as promise. Async is just syntactic candy for Promise

Async functions are created by prefixing the function declaration with the word Async

const asyncFunction = async () => {
  // Code
}
Copy the code

Async functions can be suspended with await, and this keyword can only be used in Async functions. Await returns anything returned when the async function completes.

This is the difference between promise and Async/Await

// Async / Await
const asyncGreeting = async () => 'Greetings';

// Promise
const promiseGreeting = () => new Promise(((resolve) => {
  resolve('Greetings');
}));
asyncGreeting().then(result => console.log(result));
promiseGreeting().then(result => console.log(result));
Copy the code

Async/Await looks similar to synchronous code, which is easier to understand.

Now that we’ve covered the basics, let’s move on to our real-world example!

Currency converter

Project description and setup

In this tutorial we will build a simple but educational and useful application that will improve your overall understanding of Async/Await

The program will accept the currency code we want to convert, as well as the amount. After that, the program outputs the correct exchange rate based on the data in the API.

In this application, we will receive data from two asynchronous sources:

  1. Currency layer – currencylayer.com – You need to register for free in order to access the key using the API. This API will give us the data we need to calculate exchange rates between currencies.

  2. Rest Countries – RestCountries.eu / – This API will give us information about where we can use the currency we just converted funds to.

To start, create a new directory and run NPM init, skip all steps, and install AXIOS by typing NPM I –save axios. Create a new file called currency-Converter.js.

First, enter the command:

const axios = require('axios')
Copy the code

Let’s take a closer look at Async/Await

The goal of this program is to have three asynchronous functions. The first function gets data about the currency. The second function is to get data about the country. The third function collects this information in one place and outputs it nicely to the user.

The first function receives the currency data asynchronously

We will create an asynchronous function that will take two arguments, fromCurrency and tocurrency.

const getExchangeRate = async (fromCurrency, toCurrency) => {}
Copy the code

Now we need to get the data. With Async/Await, we can assign data directly to variables; Don’t forget to register and enter your own correct access key

const getExchangeRate = async (fromCurrency, toCurrency) => {
  const response = await axios.get('http://data.fixer.io/api/latest? access_key=[yourAccessKey]&format=1');
}
Copy the code

The data from the response is available under Response.data.rates, so we can put it into variables in the response

const rate = response.data.rates;
Copy the code

Since all the data will be converted from euros, we will create a variable called euro, which will be equal to the (1 / currency) we want to convert.

const euro = 1 / rate[fromCurrency];
Copy the code

To get the exchange rate, we can multiply the euro by the currency we want to convert

const exchangeRate = euro * rate[toCurrency];
Copy the code

Finally, the function should look something like this

The second function receives country data asynchronously

We will create an asynchronous function that takes currencyCode as an argument

const getCountries = async (currencyCode) => {}
Copy the code

As mentioned earlier, we will take the data and assign it to a variable

const response = await axios.get(`https://restcountries.eu/rest/v2/currency/${currencyCode}`);
Copy the code

We then map the data and return country.name for each data

return response.data.map(country => country.name);
Copy the code

Finally, the function should look like this:

The third and final feature – merge them together

We’ll create an asynchronous function that takes fromCurrency, toCurrency, and amount as arguments

const convert = async (fromCurrency, toCurrency, amount) => {}
Copy the code

First, we get the money data

const exchangeRate = await getExchangeRate(fromCurrency, toCurrency);
Copy the code

Second, we have national data

const countries = await getCountries(toCurrency);
Copy the code

Third, we save the converted amount as a variable

const convertedAmount = (amount * exchangeRate).toFixed(2);
Copy the code

Finally, we print it all out to the user

return `${amount} ${fromCurrency} is worth ${convertedAmount} ${toCurrency}. You can spend these in the following countries: ${countries}`;
Copy the code

Putting all of the above together should look like this

Add a try/catch to handle error situations

We need to wrap all logic in try and catch errors if there are any

const getExchangeRate = async (fromCurrency, toCurrency) => {
  try {
    const response = await axios.get('http://data.fixer.io/api/latest? access_key=f68b13604ac8e570a00f7d8fe7f25e1b&format=1');
    const rate = response.data.rates;
    const euro = 1 / rate[fromCurrency];
    const exchangeRate = euro * rate[toCurrency];
    return exchangeRate;
  } catch (error) {
    throw new Error(`Unable to get currency ${fromCurrency} and  ${toCurrency}`); }};Copy the code

Repeat the same operation for the second function

const getCountries = async (currencyCode) => {
  try {
    const response = await axios.get(`https://restcountries.eu/rest/v2/currency/${currencyCode}`);
return response.data.map(country => country.name);
  } catch (error) {
    throw new Error(`Unable to get countries that use ${currencyCode}`); }};Copy the code

Because the third function only processes what the first and second functions provide, there is no need for error checking here

Finally, we can call functions and receive data

convertCurrency('USD'.'HRK', 20)
  .then((message) => {
    console.log(message);
  }).catch((error) => {
    console.log(error.message);
  });
Copy the code

You will receive the output

That’s all

You’ve made it all the way to the end, and if you’re having trouble along the way, feel free to look at the code on this repository.

You can also check it out on YouTube because I just created a channel! Click here for lots of fun stuff to come!