实现 mergePromise 函数

按顺序执行 Promise 数组并收集结果

问题

实现 mergePromise 函数,按顺序执行传入的 Promise 函数数组,并将每个 Promise 的返回值依次放入结果数组中。

要求:

  • 必须按顺序执行,等待上一个完成后再执行下一个
  • 收集所有返回值到数组中
const time = (timer) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve()
    }, timer)
  })
}

const ajax1 = () => time(2000).then(() => {
  console.log(1);
  return 1
})

const ajax2 = () => time(1000).then(() => {
  console.log(2);
  return 2
})

const ajax3 = () => time(1000).then(() => {
  console.log(3);
  return 3
})

mergePromise([ajax1, ajax2, ajax3]).then(data => {
  console.log(data); // [1, 2, 3]
})

解答

function mergePromise(ajaxArray) {
  // 存放每个 ajax 的结果
  const data = [];
  
  // 初始化一个已完成的 Promise
  let promise = Promise.resolve();
  
  // 遍历数组,依次执行
  ajaxArray.forEach(ajax => {
    promise = promise.then(ajax).then(res => {
      data.push(res);
      return data;
    });
  });
  
  return promise;
}

执行流程:

  1. 初始 promise 是一个已完成的 Promise
  2. 第一次循环:promise.then(ajax1) 执行 ajax1,结果 push 到 data
  3. 第二次循环:在上一个 promise 完成后执行 ajax2
  4. 第三次循环:在上一个 promise 完成后执行 ajax3
  5. 最终返回包含所有结果的 promise

关键点

  • 使用 Promise.resolve() 作为初始 Promise,形成链式调用
  • 每次循环将新的 Promise 赋值给 promise 变量,确保顺序执行
  • then 中收集结果并返回 data,保证链式传递
  • Promise.all() 的区别:all 是并发执行,mergePromise 是串行执行