promise和async await代码示例
本文演示了如何串行执行三个真实异步请求,不使用setTimeout,而是通过fetch请求公开API。提供了两种实现方式:1) 使用async/await依次获取文章、用户和评论数据;2) 纯Promise链式调用,每个步骤只传递单个参数(如userId→username→comments)。两种方法都实现了严格串行执行,前一个请求完成后再发起下一个请求,并展示了错误处理。代码示例使用jsonpl
·
模拟真实事件的串行执行代码示例,使用 fetch 请求三个不同的接口数据,完全不使用 setTimeout,让你看到真正异步事件如何串行执行。
✅ 串行执行三个真实接口请求(模拟真实事件)
// 每个函数表示一个异步“事件”,从服务器请求不同数据
function fetchPost() {
return fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(res => res.json());
}
function fetchUser() {
return fetch('https://jsonplaceholder.typicode.com/users/1')
.then(res => res.json());
}
function fetchComments() {
return fetch('https://jsonplaceholder.typicode.com/comments?postId=1')
.then(res => res.json());
}
✅ 使用 async/await 串行调用这三个函数
async function runTasks() {
try {
const post = await fetchPost(); // 第一个任务
console.log('Post:', post);
const user = await fetchUser(); // 第二个任务
console.log('User:', user);
const comments = await fetchComments(); // 第三个任务
console.log('Comments:', comments);
} catch (err) {
console.error('Error occurred:', err);
}
}
runTasks();
🔍 输出效果类似:
Post: { userId: 1, id: 1, title: "...", body: "..." }
User: { id: 1, name: "Leanne Graham", ... }
Comments: [ { postId: 1, id: 1, ... }, {...}, ... ]
✅ 总结:你现在看到的是:
- 真正的网络请求(真实异步事件)
- 串行依次执行:必须等待前一个请求完成后再发下一个请求
- 没有
setTimeout,无模拟成分
当然可以!下面是用 纯 Promise 写法 串行执行三个真实异步事件(网络请求)的完整代码示例。没有使用 setTimeout,请求来自公开测试 API jsonplaceholder.typicode.com,用于模拟真实异步操作:
✅ 使用 Promise 实现串行异步请求(不使用 async/await)
function fetchPost() {
return fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(res => res.json());
}
function fetchUser() {
return fetch('https://jsonplaceholder.typicode.com/users/1')
.then(res => res.json());
}
function fetchComments() {
return fetch('https://jsonplaceholder.typicode.com/comments?postId=1')
.then(res => res.json());
}
// 串行执行
fetchPost()
.then(post => {
console.log('Post:', post);
return fetchUser(); // 等待第一个完成后执行
})
.then(user => {
console.log('User:', user);
return fetchComments(); // 等待第二个完成后执行
})
.then(comments => {
console.log('Comments:', comments);
})
.catch(err => {
console.error('Error occurred:', err);
});
✅ 输出顺序说明(严格串行):
- 等
fetchPost()成功返回后,再执行fetchUser() - 等
fetchUser()成功返回后,再执行fetchComments() - 每一步都依赖于前一步成功完成
❗提示
fetch()是浏览器原生异步 API,返回 Promise。- 如果你在 Node.js 中运行,请确保安装
node-fetch或使用支持fetch的环境(Node 18+ 原生支持)。
明白了!你想要一个串行执行 + 每步只传递一个简单参数的 Promise 示例,对吧?下面是一个精简而真实的例子:
✅ 需求设定(简化版):
我们做三步串行流程,每一步只传递一个简单值(比如 id):
- 获取文章 post → 提取
userId - 用
userId获取用户 user → 提取username - 用
username去“搜索用户的评论”(模拟)
✅ 代码(每一步只传一个简单参数)
function fetchPost() {
return fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(res => res.json())
.then(post => post.userId); // 只返回 userId
}
function fetchUser(userId) {
return fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
.then(res => res.json())
.then(user => user.username); // 只返回 username
}
function searchCommentsByUsername(username) {
console.log(`🔍 Searching comments for username: ${username}`);
// 模拟结果(真实接口无法按用户名搜索评论,这里返回假数据)
return Promise.resolve([`Comment A by ${username}`, `Comment B by ${username}`]);
}
✅ 串行执行,参数逐步传递(每步只传一个)
fetchPost()
.then(userId => fetchUser(userId)) // 传 userId
.then(username => searchCommentsByUsername(username)) // 传 username
.then(comments => {
console.log('✅ Final comments:', comments);
})
.catch(err => {
console.error('❌ Error:', err);
});
✅ 输出示例
🔍 Searching comments for username: Bret
✅ Final comments: [ 'Comment A by Bret', 'Comment B by Bret' ]
✅ 总结
- 每一步都只返回一个简单值(
userId→username→comments[]) - 串行执行,前一步的结果作为参数传给下一步
- 不使用 async/await,全程纯 Promise
更多推荐

所有评论(0)