JavaScript Async Code Examples

JavaScript Async Code Examples

JavaScript is a single-threaded language, which means that it can only execute one piece of code at a time. This can make it challenging to perform long-running tasks, such as network requests, without freezing up the UI.

To solve this issue, JavaScript provides the concept of asynchronous programming, which allows you to run tasks in the background while the main thread continues to execute.

There are several ways to perform asynchronous operations in JavaScript:

Callbacks: A callback is a function that gets executed after another function has finished executing.

Example:

function fetchData(callback) {

  setTimeout(() => {

    callback({ data: “Example data” });

  }, 1000);

}

fetchData(data => console.log(data));

// Output (after 1 second): { data: “Example data” }

Promises: A Promise represents the eventual result of an asynchronous operation. A Promise can be in one of three states: pending, fulfilled, or rejected.

Example:

const fetchData = new Promise((resolve, reject) => {

  setTimeout(() => {

    resolve({ data: “Example data” });

  }, 1000);

});

fetchData.then(data => console.log(data));

// Output (after 1 second): { data: “Example data” }

async/await: async/await is a more concise and readable way to write asynchronous code, built on top of Promises. The async keyword is used to declare an asynchronous function, and the await keyword is used to wait for a Promise to be resolved.

Example:

async function fetchData() {

  return new Promise((resolve, reject) => {

    setTimeout(() => {

      resolve({ data: “Example data” });

    }, 1000);

  });

}

async function main() {

  const data = await fetchData();

  console.log(data);

}

main();

// Output (after 1 second): { data: “Example data” }

By using these asynchronous programming techniques, you can run long-running tasks in the background, without blocking the main thread and freezing the UI.