关于javascript:循环串行-Promise

16次阅读

共计 467 个字符,预计需要花费 2 分钟才能阅读完成。

业务开发中,其实常常会遇到须要串行 Promise 的场景,如果应用一般的 for 循环写法,是无奈实现冀望的成果的,解决办法就是将 Promise 以链式组装起来,代码如下:

function waitFor(time) {
  return new Promise(resolve => {setTimeout(() => {resolve();
    }, time);
  });
}

function createPromise(chain, idx) {
  return chain
    .then(() => waitFor(5000))
    .then(() => {console.log('-----', idx);
      return Promise.resolve(idx);
    });
}

function forPromise() {let currentPromise = Promise.resolve({});
  for (let i = 0; i < 10; i++) {currentPromise = createPromise(currentPromise, i);
  }
  return currentPromise;
}

forPromise();

正文完
 0