» Quick Introduction to JavaScript » 2. Advanced » 2.4 Asynchronous

Asynchronous

In JavaScript, asynchronous programming is a programming pattern that allows code to execute out of order, meaning that certain operations can be performed while waiting for others to complete, without blocking the execution of the entire program. This is particularly important when dealing with tasks that might take some time to complete, such as fetching data from a server or reading a file.

Asynchronous programming in JavaScript is typically achieved through mechanisms like callbacks, promises, and more recently, async/await.

Promises

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

A Promise is in one of these states:

  • pending: initial state, neither fulfilled nor rejected.
  • fulfilled: meaning that the operation was completed successfully.
  • rejected: meaning that the operation failed.
// Function that returns a Promise
function fetchData() {
  return new Promise((resolve, reject) => {
    // Simulating an asynchronous operation, such as fetching data from an API
    setTimeout(() => {
      const data = Math.random();
      
      // Simulating success
      if (data > 0.5) {
        resolve(data);
      } else {
        // Simulating an error
        reject("Error: Data is too low");
      }
    }, 500);
  });
}

// Using the Promise
fetchData()
  .then((result) => {
    console.log("Data fetched successfully:", result);
  })
  .catch((error) => {
    console.error("Failed to fetch data:", error);
  });

Async / Await

The async function declaration creates a binding of a new async function to a given name. The await keyword is permitted within the function body, enabling asynchronous, promise-based behavior to be written in a cleaner style and avoiding the need to explicitly configure promise chains.

async function fetchDataAsync() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = Math.random();
      if (data > 0.5) {
        resolve(data);
      } else {
        reject("Error: Data is too low");
      }
    }, 1000);
  });
}

// Using async/await
async function fetchDataUsingAsyncAwait() {
  try {
    const result = await fetchDataAsync();
    console.log("Data fetched successfully:", result);
  } catch (error) {
    console.error("Failed to fetch data:", error);
  }
}

// Calling the async function
fetchDataUsingAsyncAwait();

As you can see there, the await keyword is used to wait for the resolution of the Promise returned by fetchDataAsync. This makes the code appear more synchronous and readable.

Code Challenge

Create a function getUserInfo that fetches user information and displays it. The information includes the user's name and the number of followers.

Note: check out Promise.all().

Loading...
> code result goes here
Prev
Next