Wait for Promises in series (not parallel)

Date: 2019-02-14
(() => {
	const getPromise = (v, time) => {
      return new Promise(resolve => {
      	console.log('running', v);
      	setTimeout(() => {
        	console.log('ending', v);
        	resolve(v)
        }, time)
      });
  };

  Promise.each = (arr, fn) => {
     return arr.reduce((prev, cur, i) => prev.then(() => fn(cur, i)), Promise.resolve());
  };

  Promise.allSeries = (arrOfFn) => {
      const results = arrOfFn.map(x => null);
      return Promise.each(arrOfFn, 
      		(fn, i) => Promise.resolve(fn()).then((r) => results[i] = r))
      		.then(() => results);
  };

  Promise.allSeriesWithBluebird = (arrOfFn) => Promise.mapSeries(arrOfFn, f => f());

  // Attention: Expects an array of functions returning a promise,
  // not a regular array of promises
  Promise.allSeries([
      () => getPromise('A', 500),
      () => getPromise('B', 400),
      () => getPromise('C', 300),
      () => getPromise('D', 200),
      () => getPromise('E', 100),
      () => getPromise('F', 50),
      () => getPromise('G', 40),
      () => getPromise('H', 30)
  ]).then((results) => {
      console.log('results', results);
  });
})();
18720cookie-checkWait for Promises in series (not parallel)