使用 Async/Await异步编程

Async/Await 的基本概念

Async/Await 是 ECMAScript 2017(ES8)引入的语法糖,用于简化 Promise 的使用。async 关键字用于声明异步函数,await 用于等待 Promise 的解决(resolve)或拒绝(reject)。

async function fetchData() {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  return data;
}

错误处理机制

使用 try/catch 捕获异步操作中的错误,避免代码因未处理的 Promise 拒绝而中断。

async function fetchWithErrorHandling() {
  try {
    const response = await fetch('https://api.example.com/invalid-url');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Fetch failed:', error);
  }
}

并行执行多个异步任务

通过 Promise.all 结合 Async/Await 实现并行任务,提升执行效率。

async function fetchMultipleUrls() {
  const [userData, posts] = await Promise.all([
    fetch('https://api.example.com/users/1').then(res => res.json()),
    fetch('https://api.example.com/posts').then(res => res.json())
  ]);
  console.log({ userData, posts });
}

Async/Await 与 Promise 的对比

Async/Await 更接近同步代码的写法,可读性更高。以下是 Promise 链与 Async/Await 的对比示例:

Promise 链写法:

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

Async/Await 写法:

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}

实际应用示例:用户登录流程

模拟一个完整的用户登录流程,包括验证和数据处理。

async function login(username, password) {
  const response = await fetch('https://api.example.com/login', {
    method: 'POST',
    body: JSON.stringify({ username, password })
  });
  if (!response.ok) throw new Error('Login failed');
  return await response.json();
}

async function getUserProfile(token) {
  const response = await fetch('https://api.example.com/profile', {
    headers: { Authorization: `Bearer ${token}` }
  });
  return await response.json();
}

async function handleLogin() {
  try {
    const { token } = await login('user123', 'password');
    const profile = await getUserProfile(token);
    console.log('User profile:', profile);
  } catch (error) {
    console.error('Login error:', error.message);
  }
}

注意事项

  1. 避免在循环中误用 await:在循环中直接使用 await 会导致顺序执行,应改用 Promise.all 优化。

    // 错误示例(顺序执行)
    async processArray(array) {
      for (const item of array) {
        await processItem(item); // 效率低
      }
    }
    
    // 正确示例(并行执行)
    async processArray(array) {
      await Promise.all(array.map(item => processItem(item)));
    }
    

  2. Top-Level Await:在 ES2022 中,模块顶层可直接使用 await,无需包裹在 async 函数中。

    const data = await fetchData(); // 仅在模块中支持
    console.log(data);
    

通过以上示例和技巧,可以高效地利用 Async/Await 简化异步代码逻辑,提升开发体验。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值