Circular serial promise

Time:2021-1-14

In business development, we often encounter scenarios that require serial promise. If we use the common for loop writing method, we can’t achieve the desired effect. The solution is to chain assemble promise. The code is as follows:

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();