模拟真实事件的串行执行代码示例,使用 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);
  });

✅ 输出顺序说明(严格串行):

  1. fetchPost() 成功返回后,再执行 fetchUser()
  2. fetchUser() 成功返回后,再执行 fetchComments()
  3. 每一步都依赖于前一步成功完成

❗提示

  • fetch() 是浏览器原生异步 API,返回 Promise。
  • 如果你在 Node.js 中运行,请确保安装 node-fetch 或使用支持 fetch 的环境(Node 18+ 原生支持)。

明白了!你想要一个串行执行 + 每步只传递一个简单参数Promise 示例,对吧?下面是一个精简而真实的例子:


✅ 需求设定(简化版):

我们做三步串行流程,每一步只传递一个简单值(比如 id):

  1. 获取文章 post → 提取 userId
  2. userId 获取用户 user → 提取 username
  3. 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' ]

✅ 总结

  • 每一步都只返回一个简单值(userIdusernamecomments[]
  • 串行执行,前一步的结果作为参数传给下一步
  • 不使用 async/await,全程纯 Promise
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐