Asynchronous JavaScript

Asynchronous JavaScript is a programming technique that allows a program to run multiple tasks simultaneously. JavaScript provides several methods to achieve asynchronous programming, including callbacks, promises, and async/await. Callbacks are functions that are passed as arguments to other functions and are executed once the function is completed. Promises are objects that represent the eventual completion or failure of an asynchronous operation and allow us to handle success and failure scenarios easily. Async/await is a syntax that simplifies the use of promises and makes asynchronous code easier to read and write.

// Callback example
function fetchData(callback) {
  setTimeout(() => {
    callback('data');
  }, 2000);
}

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

// Promise example
function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('data');
    }, 2000);
  });
}

fetchData()
  .then((data) => {
    console.log(data);
  })
  .catch((error) => {
    console.error(error);
  });

// Async/await example
async function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('data');
    }, 2000);
  });
}

async function main() {
  const data = await fetchData();
  console.log(data);
}

main();