black and yellow clock landscape

Using Asynchronous JavaScript with Fetch

What Is Asynchronous JavaScript

A fundamental concept in JS is asynchronous programming.

Asynchronous is the opposite of synchronous, which in computing means executed in sequence. In synchronous JavaScript, code is executed in a straightforward sequence, step by step. However, in asynchronous JavaScript, tasks can happen concurrently, and the order of execution is not predetermined.

So asynchronous JavaScript means JavaScript that can be executed in parallel, where the steps can happen in any sequence.

If we have a routine where I do steps 1-2-3 in sequence, that takes 5 seconds every time, that's synchronous. If I send 10 messages and can expect a reply to each one somewhere between 3 seconds and 3 hours later, that's asynchronous.

This becomes important when dealing with JavaScript functions.

Normally the result of a JavaScript function can be calculated instantly: if I have the add_numbers function, and use it like add_numbers(5,7), I can get the answer - 12 - back by following a routine, in a set time.

For asynchronous JavaScript, you have to wait, for an unknown amount of time.

Examples of Asynchronous JavaScript

Suppose you want to fetch data from an external API, like sports scores or weather information. In this case, you might want to define a constant to store the API's response and then display it on your web page. However, since you can't predict how long the API call will take, you need to use asynchronous JavaScript to handle this situation gracefully.

The constant will be defined to hold the result of the API call, but it won't be calculated immediately. Instead, it will be assigned the value returned by an asynchronous function that makes the API request.

Keywords: Async and Await

Asynchronous functions in JavaScript are typically declared using two keywords: the async keyword and the await keyword. They go together usually, although you can use async without await.

async: You declare a function as asynchronous by using the async keyword in the function definition. This signifies that the function contains asynchronous operations.

await: You use the await keyword inside an asynchronous function to receive the result of an asynchronous operation. In the previous example, the result of the API call is awaited using await.

The result you receive from an asynchronous operation is called a promise. A promise is an object that holds the eventual result of an asynchronous operation. It's like a container for the value you're waiting for.

Fetch

Fetch is used to receive requests and responses from API calls.

You provide the options; fetch does the work and returns the result.

Normally you use fetch with one parameter, the URL to fetch, but you can pass a second parameter if you want more options. Here, we will only pass the URL.

The result of fetch is also a promise, like the result of await.

Fetching Data with fetch

Now that you have a basic understanding of asynchronous JavaScript and promises, let's discuss the concept of fetching data from external sources using the fetch function. The fetch function is commonly used to make network requests, such as API calls, in JavaScript.

When you use fetch, you provide the URL you want to fetch data from. The fetch function takes care of sending the request and receiving the response. Typically, you use fetch with just one parameter—the URL you want to fetch. However, you can also provide a second parameter for additional options.

Here's a practical example of using fetch to retrieve cryptocurrency data from the Binance API, which was chosen because it doesn't require authentication or anything extra (like an API key) from the developer.


import fetch from "node-fetch";

const getData = async () => {
  const url = "https://api2.binance.com/api/v3/ticker/24hr";
  console.log("Waiting...");
  const request = await fetch(url);
  const data = await request.json();
  return data;
};

getData().then(result => {
  console.log(result);
});
}

In this example, we import the fetch function and create an asynchronous function named getData. Inside the function, we define the URL from which we want to retrieve data. We then use await to wait for the fetch function to complete the network request and return a response. The response is then converted to JSON using await request.json() to obtain the data we need.

When you run this code as a Node.js script using the node script.js command, you'll see the result of the API call printed to the console. While the exact data you fetch will depend on the day and the specific cryptocurrency, you should see something similar to the following:

{
    symbol: 'EXAMPLE',
    priceChange: '0.00000025',
    priceChangePercent: '0.001',
    weightedAvgPrice: '0.00008204',
    ....

Conclusion

Now you know how to use an asynchronous function in JavaScript and the fetch function to retrieve data from an external API. Asynchronous JavaScript allows you to work with operations that have unpredictable timing, making it a vital tool for building responsive web applications and handling various tasks concurrently.

To learn more, consider finding other APIs and integrating this asynchronous function into a web application. The more you practice, the more comfortable you'll become with asynchronous JavaScript and fetching data from external sources.

In conclusion, mastering asynchronous programming in JavaScript, along with understanding how to properly use the fetch function, will empower you to build dynamic and responsive web applications that can handle a wide range of useful tasks.

So, think about how you can use asynchronous JavaScript in your app - and then go and do it.

Good luck!