Promise数组的串行执行

Promise数组的串行执行

利用递归的方式

  let promises = []; // 初始化promise数组

  for (let i = 0; i < 5; i++) {
    promises.push(
      new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(i);
        }, 1000 * (i + 1));
      })
    );
  }

  // 递归方式处理
  function serial(promises) {
    const maxCount = promises.length;
    let count = 0;

    function next(promise) {
      if (count >= maxCount) return;
      promise.then(res => {
        count++;
        next(promises[count]);
      })
    }
    next(promises[count]);
  };

  serial(promises);	

利用ES8语法糖 async/await

  // 利用async/await进行串行操作
  function asyncFn(promises) {
    for (const promise of promises) {
      await promise()
    }
  }

  asyncFn(promises);

利用Generator函数

  // 利用Generator
  function serial(promises) {
    const maxCount = promises.length;
    let count = 0;
  
    function* gen (promise) {
      let y = yield promise;
    }

    function next(promise) {
      if (count >= maxCount) return;
      const res = gen(promise).next();
      res.value.then((val) => {
        count++;
        next(promises[count]);
      });
    }
    next(promises[0]);
  }

  serial(promises);
posted @ 2020-12-04 10:59  chenfengami  阅读(892)  评论(0编辑  收藏  举报