Promise 链式工作流
中等 约 35 分钟
你将构建什么
一个使用 Promise 链接三个异步步骤的模拟数据流水线,含错误处理和通过 Promise.all 的并行增强。
学习目标
- 用 then 链接 Promise 实现顺序异步步骤
- 用 catch 处理错误、用 finally 清理
- 用 Promise.all 并行运行独立步骤
- 通过异步函数流水线转换数据
前置要求
- 函数与回调
- 数组方法(map、flatMap)
- Promise 概念(pending、fulfilled、rejected)
步骤
- 1
创建模拟异步 API
构建三个返回 Promise 的函数,延迟后 resolve:getUser(id)、getPosts(userId)、getComments(postId)。用 setTimeout 模拟网络延迟。
代码function delay(ms, value) { return new Promise(resolve => setTimeout(() => resolve(value), ms)); } function getUser(id) { return delay(100, { id, name: 'User ' + id }); } function getPosts(userId) { return delay(150, [{ id: 1, userId, title: 'Post A' }, { id: 2, userId, title: 'Post B' }]); } function getComments(postId) { return delay(100, [{ postId, text: 'Great!' }, { postId, text: 'Thanks' }]); }预期结果
每个函数返回一个延迟后 resolve 模拟数据的 Promise。
- 2
链式连接 user → posts
用 .then 先获取用户再获取其帖子。每个 then 接收上一步结果并返回下一个 Promise,形成链条。
代码getUser(1) .then(user => { console.log('User:', user); return getPosts(user.id); }) .then(posts => console.log('Posts:', posts));预期结果
约 250ms 后,依次打印用户和帖子。
- 3
并行用评论增强帖子
为每个帖子获取评论。由于帖子相互独立,用 Promise.all 并行获取所有评论而非顺序执行。
代码getUser(1) .then(user => getPosts(user.id).then(posts => ({ user, posts }))) .then(({ user, posts }) => { return Promise.all( posts.map(post => getComments(post.id).then(comments => ({ ...post, comments }))) ).then(enrichedPosts => ({ user, posts: enrichedPosts })); }) .then(result => console.log('Enriched:', result));预期结果
每个帖子现在包含 comments 数组,并行获取。
- 4
添加错误处理
追加 .catch 处理链中任何 rejection,用 .finally 记录流水线无论结果如何都已完成。
代码.catch(err => console.error('Pipeline failed:', err)) .finally(() => console.log('Pipeline done'));预期结果
若任一步骤 reject,错误被打印;'Pipeline done' 总会打印。
- 5
测试完整流水线
运行完整链条并验证最终结果形状:{ user, posts: [{ id, userId, title, comments }] }。计时确认并行获取比顺序更快。
代码const start = Date.now(); // ... full chain ... // Inside final .then: console.log('Took', Date.now() - start, 'ms'); // Sequential would be ~100+150+100+100 = 450ms // Parallel comments: ~100+150+100 = 350ms预期结果
流水线约 350ms(并行)完成,而非 450ms(顺序)。
自己动手试试
起始代码
function getUser(id) { /* TODO: return Promise */ }
function getPosts(userId) { /* TODO */ }
function getComments(postId) { /* TODO */ }
// TODO: chain them with then/catch/finally解决方案代码
getUser(1).then(u => getPosts(u.id).then(p => ({u, p}))).then(({u, p}) => Promise.all(p.map(x => getComments(x.id).then(c => ({...x, c})))).then(ep => ({u, p: ep}))).then(console.log).catch(console.error).finally(() => console.log('done'));你学到了什么
你构建了含顺序和并行步骤的真实异步数据流水线——Promise 链是每个 Web 应用中基于 fetch 的数据加载的基础。
相关资源
相关课程
- Promise
then、catch、finally 和 Promise.all。
- Async/Await
同一模式的现代语法。
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。