async/await 使用

async/await 是 JavaScript 中处理异步操作的语法糖,基于 Promise

一、基础语法

1. async 函数

  • 用 async 声明的函数会自动返回一个 Promise 对象。
  • 函数内部的 return 值会成为这个 Promise 的 resolve 结果。
async function fn() {
  return '成功结果'; // 等同于 return Promise.resolve('成功结果')
}

// 调用 async 函数
fn().then(result => {
  console.log(result); // 输出:成功结果
});

2. await 关键字

  • 只能在 async 函数内部使用,用于等待一个 Promise 完成。
  • 会暂停当前 async 函数的执行,直到 Promise 状态变为 resolved 或 rejected
async function getData() {
  // 等待一个 Promise(如接口请求)
  const result = await new Promise((resolve) => {
    setTimeout(() => {
      resolve('异步数据');
    }, 1000);
  });

  console.log(result); // 1秒后输出:异步数据
  return result;
}

getData();

 

二、错误处理

async function fetchData() {
  try {
    // 假设这是一个可能失败的异步操作
    const result = await Promise.reject(new Error('请求失败'));
    console.log('成功:', result); // 不会执行
  } catch (error) {
    console.error('失败:', error.message); // 输出:失败:请求失败
  }
}

fetchData();

 

三、常见使用场景

1. 处理接口请求(结合 axios)

// 假设 api.fetchUser() 是返回 Promise 的接口函数
async function getUser() {
  try {
    const user = await api.fetchUser(123); // 等待接口返回
    const posts = await api.fetchPosts(user.id); // 依赖上一个接口的结果
    console.log('用户文章:', posts);
  } catch (error) {
    console.error('接口错误:', error);
  }
}

 

2. 并行执行多个异步操作(配合 Promise.all

async function loadMultipleData() {
  try {
    // 同时发起3个独立请求,等待所有完成
    const [user, goods, orders] = await Promise.all([
      api.fetchUser(),
      api.fetchGoods(),
      api.fetchOrders()
    ]);
    console.log('用户:', user, '商品:', goods, '订单:', orders);
  } catch (error) {
    console.error('至少一个请求失败:', error);
  }
}

四、注意事项

    1. await 只能在 async 函数中使用
      普通函数中使用 await 会报错

 

posted on 2025-08-22 18:38  Mc525  阅读(21)  评论(0)    收藏  举报

导航