Home Web Front-end JS Tutorial Asynchronous JavaScript: Promises, Async/Await, and Callbacks

Asynchronous JavaScript: Promises, Async/Await, and Callbacks

Aug 28, 2024 am 06:05 AM

Asynchronous JavaScript: Promises, Async/Await, and Callbacks

Originally published on Makemychance.com

Asynchronous programming is a core concept in JavaScript, which allows you to perform tasks without blocking the execution of other code. This becomes especially important when dealing with operations that take time to complete, such as network requests, file I/O, or timers. In this article, we will explore the three main techniques for handling asynchronous code in JavaScript: Callbacks, Promises, and Async/Await.

1. Callbacks

Callbacks are the oldest way of handling asynchronous operations in JavaScript. A callback is simply a function passed as an argument to another function, which is then executed after the completion of a task.

function fetchData(callback) {
  setTimeout(() => {
    callback("Data received");
  }, 2000);
}

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

Copy after login

In the example above, fetchData simulates a network request with setTimeout, and the callback function logs the message after the request is completed.

Callback Hell

One of the downsides of using callbacks is the infamous “callback hell” or “pyramid of doom,” where multiple nested callbacks make the code difficult to read and maintain.

fetchData((message) => {
  console.log(message);
  fetchMoreData((moreData) => {
    console.log(moreData);
    fetchEvenMoreData((evenMoreData) => {
      console.log(evenMoreData);
      // And so on...
    });
  });
});

Copy after login

2. Promises

Promises, introduced in ES6, offer a cleaner approach to handling asynchronous tasks, helping to overcome the challenges of deeply nested callbacks. Essentially, a promise is an object that symbolizes the outcome of an asynchronous operation, whether it successfully completes or fails, and it provides a structured way to handle the resulting value.

function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("Data received");
    }, 2000);
  });
}

fetchData()
  .then((message) => {
    console.log(message);
    return "Next step";
  })
  .then((nextMessage) => {
    console.log(nextMessage);
  })
  .catch((error) => {
    console.error("Error:", error);
  });

Copy after login

In this example, fetchData returns a promise. The .then() method is used to handle the resolved value of the promise, and .catch() is used to handle any errors.

Chaining Promises

Promises can be chained, making the code more readable and maintainable.

fetchData()
  .then((message) => {
    console.log(message);
    return fetchMoreData();
  })
  .then((moreData) => {
    console.log(moreData);
    return fetchEvenMoreData();
  })
  .then((evenMoreData) => {
    console.log(evenMoreData);
  })
  .catch((error) => {
    console.error("Error:", error);
  });

Copy after login

3. Async/Await

Async/Await, introduced in ES8 (2017), is a syntactic sugar built on top of promises, making asynchronous code look and behave more like synchronous code.

async function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("Data received");
    }, 2000);
  });
}

async function processData() {
  try {
    const message = await fetchData();
    console.log(message);
    const moreData = await fetchMoreData();
    console.log(moreData);
    const evenMoreData = await fetchEvenMoreData();
    console.log(evenMoreData);
  } catch (error) {
    console.error("Error:", error);
  }
}

processData();

Copy after login

In this example, the processData function uses the await keyword to wait for the promise returned by fetchData to resolve. This makes the code much cleaner and easier to follow compared to promise chaining.

Error Handling

Error handling in async/await is done using try...catch blocks, providing a straightforward way to handle errors without the need for a .catch() method.

async function processData() {
  try {
    const data = await fetchData();
    console.log(data);
  } catch (error) {
    console.error("Error:", error);
  }
}
Copy after login

The above is the detailed content of Asynchronous JavaScript: Promises, Async/Await, and Callbacks. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Replace String Characters in JavaScript

jQuery Check if Date is Valid jQuery Check if Date is Valid Mar 01, 2025 am 08:51 AM

jQuery Check if Date is Valid

jQuery get element padding/margin jQuery get element padding/margin Mar 01, 2025 am 08:53 AM

jQuery get element padding/margin

10 jQuery Accordions Tabs 10 jQuery Accordions Tabs Mar 01, 2025 am 01:34 AM

10 jQuery Accordions Tabs

10 Worth Checking Out jQuery Plugins 10 Worth Checking Out jQuery Plugins Mar 01, 2025 am 01:29 AM

10 Worth Checking Out jQuery Plugins

HTTP Debugging with Node and http-console HTTP Debugging with Node and http-console Mar 01, 2025 am 01:37 AM

HTTP Debugging with Node and http-console

Custom Google Search API Setup Tutorial Custom Google Search API Setup Tutorial Mar 04, 2025 am 01:06 AM

Custom Google Search API Setup Tutorial

jquery add scrollbar to div jquery add scrollbar to div Mar 01, 2025 am 01:30 AM

jquery add scrollbar to div

See all articles