Today let’s talk about how to master Async/Await with examples

2. Instance – Currency converter receives asynchronous data from two apis’ s.

Introduction Async/await is a new way to write asynchronous code. It’s based on promises, so it’s non-blocking. The biggest difference is that asynchronous code looks closer to synchronous code. That’s the key to it. The previous asynchronous code options were Callbacks and Promises.

Callback function program

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

The problem with callbacks — the infamous callback hell where nested callbacks within callback functions can quickly look like this:

The callback hell


Promises program

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 Promise function returns a Promise that represents the process of the function. The resolve function signals to the Promise instance that it has completed. We can then call the promise function’s then() and.catch(): then – to run the callback passed to the promise after it completes. Catch – Runs a callback that is passed to when an error occurs.

The Async function gives us a clean and concise syntax that allows us to write less code to achieve the same results as Promises. Async is just promises grammar candy. Async functions are created by prefixing Async to the function declaration as follows:

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

Asynchronous functions can be paused with await, and await is a keyword that can only be used in asynchronous functions. Await returns anything returned after the asynchronous function has finished. This is the difference between Promises and Async/Wait: Promises are promises.

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

Async/ Wait looks similar to synchronous code, and synchronous code is easier to understand. Now that we’ve covered the basics, let’s move on to real world examples!

Currency Converter Project Description and Setup In this tutorial, we will build a simple but educational and useful application that will improve your overall knowledge of Async/ Wait. This program will indicate the amount and currency code we want to convert from one currency code to another. The program will then output the correct exchange rate based on the data from the API.

In this application, we will receive data from two asynchronous sources: 1. The currencylayer — currencylayer.com — you need to register for free in order to use the API to access the key. This API will give us the data we need to calculate exchange rates between currencies. 2. Other countries — RestCountries.eu / — This API will tell us…

First, create a new directory and run NPM init, skipping all steps, and then type NPM I –save axios. Install axios. Create a new folder named currency-Converter.js.

Let’s dig into async/await. Our goal for this program is to have three functions. Not one, not two, but three asynchronous functions. The first function is to get data about the currency. The second function is to get data about the country. The third function will gather the information in one place and output it nicely to the user.

We will create an asynchronous function that will take fromCurrency and toCurrency arguments.

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

Now we need to get the data. With async/ Wait, we can assign data directly to a variable; 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 in the response is available under response.data.rates, so we can put it in the variable below the response:

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

Since everything is converted from euros, below, we will create a variable called euro, which will be equal to 1/ the currency we want to convert:

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

To get an exchange rate, we can multiply euros by the currency we want to convert to:

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

Finally, the function should look like this:

The second function – receives country data asynchronously

We will create an asynchronous function that will take 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

Then, we map the data and return country.name:

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 monetary data:

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

Second, we get the country data:

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

Third, 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

All of this should end up like this:

Add a try/catch to handle error cases we need to wrap all logic in a try, and if there is an error, catch it:

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 to check for errors. Finally, we can call the function and receive data:

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

The output you will receive:

That’s all for today’s sharing. I hope this article can help you!

Click like, so that more people can see this content (collection does not click like, are playing rogue -_-) pay attention to the public number “new front-end community”, enjoy the first article experience! Focus on conquering one front-end technical difficulty every week.