1

业务开发中,其实经常会遇到需要串行 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();

tgshell
31 声望0 粉丝