async/await 简要介绍

📋 一句话概括

async/await用同步写法处理异步操作的 JavaScript 语法糖,基于 Promise。

🎯 核心作用

让异步代码看起来和同步代码一样清晰,告别回调地狱。

📝 基本语法

// 1. async 函数
async function fetchData() {
  // 2. await 等待 Promise 完成
  const data = await getDataFromAPI()
  return data
}

🔧 三个关键点

1. async 函数

// async 函数总是返回 Promise
async function demo() {
  return 42
}

// 等价于
function demo() {
  return Promise.resolve(42)
}

2. await 表达式

// await 只能在 async 函数中使用
// 它会"暂停"执行,等待 Promise 完成
const result = await somePromise()

3. 错误处理

// 使用 try/catch
async function safeFetch() {
  try {
    const data = await fetchData()
    return data
  } catch (error) {
    console.error('失败:', error)
  }
}

💡 经典示例对比

回调地狱 → Promise → async/await

// ❌ 回调地狱
getData(data => {
  getMore(data, more => {
    getEvenMore(more, result => {
      console.log(result)
    })
  })
})

// ✅ Promise
getData()
  .then(data => getMore(data))
  .then(more => getEvenMore(more))
  .then(result => console.log(result))
  .catch(error => console.error(error))

// ✅ async/await(最清晰)
async function getResult() {
  try {
    const data = await getData()
    const more = await getMore(data)
    const result = await getEvenMore(more)
    console.log(result)
  } catch (error) {
    console.error(error)
  }
}

主要特点

优点

  • 代码清晰:像写同步代码一样简单
  • 错误处理:可用传统的 try/catch
  • 调试友好:调用栈更清晰
  • 逻辑直观:顺序执行,易于理解

注意事项

  • ⚠️ 必须在 async 函数内:await 不能单独使用
  • ⚠️ 需要错误处理:忘记 try/catch 会导致未处理错误
  • ⚠️ 可能阻塞:多个 await 会顺序执行,需要时用 Promise.all

🔄 实际用例

// 用户登录流程
async function userLogin(username, password) {
  try {
    // 1. 验证用户
    const user = await validateUser(username, password)

    // 2. 获取用户信息
    const profile = await getUserProfile(user.id)

    // 3. 获取用户权限
    const permissions = await getUserPermissions(user.id)

    // 4. 返回完整数据
    return { user, profile, permissions }
  } catch (error) {
    console.error('登录失败:', error)
    throw error
  }
}

📈 性能优化

// 顺序执行(慢)
const a = await task1()  // 等5秒
const b = await task2()  // 等3秒
// 总共:8秒

// 并行执行(快)
const [a, b] = await Promise.all([task1(), task2()])
// 总共:5秒(取最长的)

🎓 记住这几点

  1. async 函数 → 总是返回 Promise
  2. await → 只能在 async 函数中使用
  3. try/catch → 必须处理错误
  4. Promise.all → 多个异步任务并行执行

这就是 async/await 的核心!它让异步编程变得简单直观,是现代 JavaScript 开发的必备技能。