JavaScript Promises and Async/Await

微笑向暖 2019-10-15 ⋅ 10 阅读

JavaScript is a single-threaded programming language, meaning it only executes one task at a time. However, modern JavaScript provides several ways to handle concurrency and asynchronous operations. In this blog post, we will explore Promises and the newer Async/Await syntax that makes working with asynchronous code much cleaner and easier to understand.

Promises

Promises were introduced in ES6 as a way to handle asynchronous operations in a more organized and controlled manner. A Promise represents the eventual completion (or failure) of an asynchronous operation and allows you to attach callbacks to it. Here's how you can create and use a Promise:

const fetchData = new Promise((resolve, reject) => {
  // Simulating an asynchronous operation
  setTimeout(() => {
    const data = "Hello, World!";
    if (data) {
      resolve(data); // On successful completion
    } else {
      reject("An error occurred!"); // On error
    }
  }, 2000);
});

fetchData
  .then((data) => {
    console.log(data); // Output: Hello, World!
  })
  .catch((error) => {
    console.log(error); // Output: An error occurred!
  });

Promises have three states: pending, fulfilled, and rejected. When a Promise is pending, it means the asynchronous operation is still running. When it is fulfilled, it means the operation is completed successfully. And when it is rejected, it means an error occurred during the operation. Promises allow you to chain .then() and .catch() methods to handle the success and failure of the operation respectively.

Async/Await

Async/Await is a newer syntax introduced in ES8 and built on top of Promises. It provides a cleaner and more readable way to write asynchronous code. The async keyword declares a function to be asynchronous, and the await keyword is used to pause the execution of the function until a Promise is resolved. Here's an example of using Async/Await:

const fetchData = () => {
  return new Promise((resolve, reject) => {
    // Simulating an asynchronous operation
    setTimeout(() => {
      const data = "Hello, World!";
      if (data) {
        resolve(data); // On successful completion
      } else {
        reject("An error occurred!"); // On error
      }
    }, 2000);
  });
}

const fetchDataAsync = async () => {
  try {
    const data = await fetchData();
    console.log(data); // Output: Hello, World!
  } catch (error) {
    console.log(error); // Output: An error occurred!
  }
}

fetchDataAsync();

In the above example, the fetchDataAsync function is declared as asynchronous using the async keyword. Inside the function, the await keyword is used to pause the execution until the fetchData Promise is resolved. This makes the code look more synchronous and easier to understand.

Concurrency with Promises and Async/Await

Concurrency refers to the ability to execute multiple tasks or operations simultaneously. While JavaScript is single-threaded, Promises and Async/Await allow for concurrent execution of asynchronous operations.

Using Promises, you can start multiple asynchronous operations and then wait for all of them to complete using Promise.all():

const fetchUsers = () => {
  return new Promise((resolve, reject) => {
    // Simulating an asynchronous operation
    setTimeout(() => {
      const users = ["John", "Jane", "Bob"];
      resolve(users);
    }, 2000);
  });
}

const fetchPosts = () => {
  return new Promise((resolve, reject) => {
    // Simulating an asynchronous operation
    setTimeout(() => {
      const posts = ["Post 1", "Post 2", "Post 3"];
      resolve(posts);
    }, 3000);
  });
}

Promise.all([fetchUsers(), fetchPosts()])
  .then(([users, posts]) => {
    console.log(users); // Output: ["John", "Jane", "Bob"]
    console.log(posts); // Output: ["Post 1", "Post 2", "Post 3"]
  })
  .catch((error) => {
    console.log(error);
  });

Async/Await also allows for concurrent execution using Promise.all():

const fetchDataAsync = async () => {
  try {
    const [users, posts] = await Promise.all([fetchUsers(), fetchPosts()]);
    console.log(users); // Output: ["John", "Jane", "Bob"]
    console.log(posts); // Output: ["Post 1", "Post 2", "Post 3"]
  } catch (error) {
    console.log(error);
  }
}

fetchDataAsync();

By utilizing Promises and Async/Await, JavaScript provides powerful tools for handling asynchronous code and enabling concurrency. These features make it easier to write and maintain code that deals with complex and time-consuming operations, improving the overall performance and user experience of web applications.


全部评论: 0

    我有话说: