async/await 是 JavaScript 中的语法糖,用于简化异步代码的编写。它允许你在异步代码中使用同步风格的语法,使代码更易于阅读和维护。

用法:

  • 使用关键字 async 声明一个异步函数
  • 在函数中使用 await 来等待异步操作完成
async function getData() {
  const response = await fetch('https://api.example.com');
  const data = await response.json();
  console.log(data);
}

Promise 的区别:

  • async/await 是在 Promise 的基础上构建的,所以在使用 async/await 时仍然需要使用 Promise
  • async/await 提供了更直观的语法来处理异步操作,而 Promise 更像是一种编程模式。
  • async/await 更符合人类思维方式,更容易理解。
  • 当使用 async/await 时,可以使用 try/catch 来处理错误,这样和处理同步代码的错误方式是一致的,而在使用 Promise 时,则需要使用.catch() 方法来处理错误。
async function getData() {
  try {
    const response = await fetch('https://api.example.com');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}
  • async/await 还支持同时处理多个异步操作,可以使用 Promise.all() 方法来实现。
const fetchData = async () => {
    const [users, posts] = await Promise.all([
        fetch('/users').then(response => response.json()),
        fetch('/posts').then(response => response.json())
    ]);
    console.log(users, posts);
}
  • 使用 async/await 时,可以在任意位置使用 return 来终止函数的执行,而使用 Promise 时,只能在 thencatch 函数中使用 return
  • 使用 async/await 的函数始终返回一个 promise。如果在函数中使用了 return,则 promise 的结果为该返回值。如果函数没有使用 return,则 promise 的结果为 undefined

总之,async/await 是在 Promise 的基础上提供了更易于阅读和维护的语法,使得异步编程更符合人类思维方式,但它并不是替代Promise,而是建立在Promise之上的语法糖。在异步编程中,需要根据情况来选择使用 Promise 或者 async/await