theydy / notebook

记录读书笔记 + 知识整理,vuepress 迁移中 https://theydy.github.io/notebook/
0 stars 0 forks source link

实现 mergePromise #35

Open theydy opened 3 years ago

theydy commented 3 years ago
// 实现 mergePromise
// 最后输出: 1, 2, 3 'done' [1, 2, 3]
const timeout = (ms) =>
  new Promise((resolve, reject) => {
    setTimeout(() => resolve(), ms);
  });

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

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

const ajax3 = () =>
  timeout(2000).then(() => {
    console.log('3');
    return 3;
  });

const mergePromise = (ajaxArray) => {
  const result = [];
  const list = ajaxArray.slice();
  return new Promise(resolve => {
      const helper = () => {
          if (!list.length) {
            return resolve(result)
          }
          const ajax = list.shift();
          ajax().then(res => {
            result.push(res);
            helper();
          })
      }

      helper();
  })
};

mergePromise([ajax1, ajax2, ajax3]).then((data) => {
  console.log('done');
  console.log(data);
});
theydy commented 3 years ago

const mergePromise = function(args) {
  const list = args.slice();
  const result = [];
  let target;

  return new Promise(async (resolve) => {
    while((target = list.shift(), target)){
      const res = await target();
      result.push(res);
    }

    resolve(result);
  });
}