Home > Web Front-end > JS Tutorial > Javascript: async/await

Javascript: async/await

Mary-Kate Olsen
Release: 2024-11-29 12:06:12
Original
483 people have browsed it

async and await are powerful features in JavaScript that make working with Promises easier and more readable. They allow you to write asynchronous code that looks and behaves like synchronous code. Here's a quick overview:

async Function

  • Definition: An async function is a function that returns a Promise. It allows you to use await within it.
  • Syntax:
  async function myFunction() {
    // Your code here
  }
Copy after login

await Keyword

  • Definition: The await keyword can only be used inside an async function. It pauses the execution of the async function and waits for the Promise to resolve or reject.
  • Syntax:
  let result = await somePromise;
Copy after login

Example

Here's a simple example to demonstrate how async and await work together:

function fetchData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('Data fetched');
    }, 2000);
  });
}

async function getData() {
  console.log('Fetching data...');
  const data = await fetchData();
  console.log(data);
}

getData();
Copy after login

In this example:

  1. fetchData is a function that returns a Promise, which resolves after 2 seconds.
  2. getData is an async function that uses await to wait for fetchData to resolve.
  3. When getData is called, it logs "Fetching data...", waits for fetchData to resolve, and then logs "Data fetched".

Benefits

  • Readability: async/await makes asynchronous code look more like synchronous code, which can be easier to read and understand.
  • Error Handling: You can use try...catch blocks with async/await to handle errors more cleanly.

Error Handling Example

async function getData() {
  try {
    console.log('Fetching data...');
    const data = await fetchData();
    console.log(data);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

getData();
Copy after login

In this example, if fetchData were to reject, the error would be caught by the catch block, and "Error fetching data:" would be logged along with the error message.


Thank you for reading!
I hope you found this article helpful and informative. If you enjoyed it or learned something new, feel free to share your thoughts in the comments or connect with me.

If you'd like to support my work and help me create more content like this, consider buying me a coffee. Your support means the world and keeps me motivated!

Thanks again for stopping by! ?

Javascript: async/await

The above is the detailed content of Javascript: async/await. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template