Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Asynchronous JavaScript (Callbacks, Promises, Async/Await)

Asynchronous JavaScript (Callbacks, Promises, Async/Await)

Asynchronous JavaScript is a crucial aspect of web development, allowing you to perform tasks without blocking the main execution thread. This is particularly important for tasks like fetching data from servers, handling user input, and animations. Here's an introduction to asynchronous JavaScript using callbacks, promises, and async/await:

Callbacks:

Callbacks are functions that are passed as arguments to other functions. They are executed after the completion of a task.

function getData(callback) {
  setTimeout(() => {
    let data = "Some data";
    callback(data);
  }, 2000);
}

function processData(data) {
  console.log(`Processing data: ${data}`);
}

getData(processData);
 

Promises:

Promises provide a cleaner way to work with asynchronous code. They represent the eventual completion or failure of an asynchronous operation.

function getData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      let success = true;
      if (success) {
        resolve("Some data");
      } else {
        reject("Error occurred");
      }
    }, 2000);
  });
}

getData()
  .then(data => {
    console.log(`Data received: ${data}`);
  })
  .catch(error => {
    console.error(`Error: ${error}`);
  });
 

Async/Await:

Async/await is a modern way to work with asynchronous code. It provides a more synchronous style of writing code while still being asynchronous under the hood.

async function getData() {
  try {
    let data = await fetch('https://api.example.com/data');
    let json = await data.json();
    return json;
  } catch (error) {
    console.error(`Error: ${error}`);
  }
}

getData().then(data => {
  console.log(`Data received: ${data}`);
});
 

Error Handling in Promises and Async/Await:

Promises and async/await provide mechanisms for error handling. In promises, you use .catch() to handle errors. In async/await, you can use a try-catch block.

async function getData() {
  try {
    let data = await fetch('https://api.example.com/data');
    let json = await data.json();
    return json;
  } catch (error) {
    console.error(`Error: ${error}`);
    throw error; // Rethrow the error if needed
  }
}