Skip to content

Async/Await 数据获取器

中等 约 35 分钟

你将构建什么

一个含指数退避重试包装器、通过 Promise.all 并发获取、用 try/catch 清晰处理错误的异步获取器。

学习目标

  • 用 async/await 编写顺序异步代码
  • 用 try/catch 处理错误
  • 用 Promise.all + await 运行并发获取
  • 实现带指数退避的重试包装器

前置要求

  • Promise 链(见 project-11)
  • try/catch 错误处理
  • async/await 语法

步骤

  1. 1

    编写异步获取器

    创建一个用 await 顺序调用三个 API 的 async 函数。await 解包 Promise,让你能写出读起来像同步的异步代码。

    代码
    async function fetchUserData(userId) {
      const user = await getUser(userId);
      const posts = await getPosts(user.id);
      return { user, posts };
    }

    预期结果

    调用 fetchUserData(1) 返回一个 resolve 为 { user, posts } 的 Promise。

  2. 2

    添加 try/catch 错误处理

    用 try/catch 包裹 await。若任一 await reject,控制跳转到 catch。记录错误并返回回退值。

    代码
    async function fetchUserData(userId) {
      try {
        const user = await getUser(userId);
        const posts = await getPosts(user.id);
        return { user, posts };
      } catch (err) {
        console.error('Fetch failed:', err);
        return { user: null, posts: [] };
      }
    }

    预期结果

    若 getUser reject,函数返回回退值而非抛出。

  3. 3

    用 Promise.all 并发获取

    若需要多个独立数据,用 await Promise.all([...]) 并发获取而非逐个等待。

    代码
    async function fetchDashboard(userId) {
      const [profile, notifications, settings] = await Promise.all([
        getProfile(userId),
        getNotifications(userId),
        getSettings(userId),
      ]);
      return { profile, notifications, settings };
    }

    预期结果

    三个获取并行运行;总时间为最慢者,而非三者之和。

  4. 4

    编写重试包装器

    创建 async 函数 withRetry(fn, retries, delay),调用 fn,reject 时等待并重试最多 retries 次,使用指数退避。

    代码
    async function withRetry(fn, retries = 3, delay = 100) {
      for (let attempt = 0; attempt <= retries; attempt++) {
        try {
          return await fn();
        } catch (err) {
          if (attempt === retries) throw err;
          const wait = delay * Math.pow(2, attempt);
          console.log(`Retry ${attempt + 1} in ${wait}ms`);
          await new Promise(r => setTimeout(r, wait));
        }
      }
    }

    预期结果

    withRetry(() => flakyApi(), 3) 最多重试 3 次,等待 100、200、400ms。

  5. 5

    组合并测试

    用 withRetry 包裹 fetchUserData 中的不稳定 API。用一个 50% 失败率的 API 测试,确认重试生效。

    代码
    let calls = 0;
    async function flakyApi() {
      calls++;
      if (Math.random() < 0.5) throw new Error('Random fail');
      return 'success on call ' + calls;
    }
    
    (async () => {
      const result = await withRetry(flakyApi, 3);
      console.log('Result:', result, 'after', calls, 'calls');
    })();

    预期结果

    最终成功,打印结果和调用次数(1-4)。

自己动手试试

你学到了什么

你掌握了 async/await——编写异步 JS 的现代方式——并构建了带指数退避的生产级重试包装器,用于真实 fetch 库。

相关资源

相关课程

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回主题