"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > async / await

async / await

Published on 2024-11-01
Browse:510

async / await

async / await

async / await is a newer way of writing asynchronous code compared to promises. The main advantages of async/await are improved readability and the avoidance of promise chaining. Promises can become long, hard to read, and may contain deeply nested callbacks that can be difficult to debug.

Example

Recall our fetch from before.

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error))
  .finally(() => console.log('All done'));

Using async/await, the code can be refactored to look like this:

async function fetchData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  } finally {
    console.log('All done');
  }
}

fetchData();

While it may be a few more lines of code, this version is easier to read because it resembles a normal synchronous function. Additionally, if the functions inside the .then() statements were more complex, readability and debuggability would be even more impacted. The async/await example is far clearer.

Example 2: Ordering food from a restaurant

Structure of async/await

An async/await function has two essential parts: async and await. The async keyword is added before a function declaration, and await is used when an asynchronous task begins.

Let’s illustrate this with an example of ordering food from a restaurant:

// Simulate the order process with async/await
async function foodOrder() {
  console.log("Ordering food...");
  await new Promise(resolve => setTimeout(resolve, 2000)); // Wait 2 seconds for food to be prepared
  return "Your food is ready!";
}

// Simulate the eating process
function eatFood(order) {
  console.log(order); // This logs "Your food is ready!"
  console.log("Enjoying the meal!");
}

// Simulate continuing the conversation
function continueConversation() {
  console.log("While waiting, you continue chatting with friends...");
}

async function orderFood() {
  console.log("You've arrived at the restaurant.");
  const order = await foodOrder(); // Place the order and wait for it to be ready
  continueConversation(); // Chat while waiting
  eatFood(order); // Eat the food once it arrives
}

orderFood();

The output will be

You've arrived at the restaurant.
Ordering food...
While waiting, you continue chatting with friends...
Your food is ready!
Enjoying the meal!
Release Statement This article is reproduced at: https://dev.to/wolfmath/async-await-13bn?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3