Serial Promises

Chaining an array of promises

by amindunited

JavaScript

const delayedTask = (_name) => {
	const promise = new Promise((resolve, reject) => {
  	setTimeout(() => {
    	console.log('Delayed Promise...', _name);
      resolve(_name);
    }, 1000);
  });
  return promise;
}

const delayedTask_2 = () => {
	const promise = new Promise((resolve, reject) => {
  	setTimeout(() => {
    	console.log('Delayed Promise...toooooooooooo');
      resolve();
    }, 1000);
  });
  return promise;
}

const myTasks = [
	() => delayedTask('task_1'),
  () => delayedTask('task_2'),
  () => delayedTask('task_3'),
  () => delayedTask('task_4'),
  () => delayedTask('task_5'),
  delayedTask_2
];


/**
 *	promiseArray array<any> an array of functions that return promises
 */
function serialisePromises(promiseArray) {
	/**
   * The promiseChain is really just an array built from the promiseArray
   * The currentTask is the the task at the current index of the promiseArray
   */
  return promiseArray.reduce((promiseChain, currentTask) => {
    console.log('??', promiseChain, currentTask);
    /**
     * We now want to add a 'then' to the resolve of the previous promise
     * ie: arrayOfPreviousPromises.then(() => nextPromise) 
     */
    return promiseChain.then((chainResults) => {

      return currentTask.apply().then((currentResult) => {
      	// Finally return the previous results, in an array with this result
        return [...chainResults, currentResult]
      })
    })
  }, Promise.resolve([]))
}

serialisePromises(myTasks).then((allDone)=> { console.log('allDone ', allDone); });