How to run Promises in series with Javascript

The Promise.all() method is very responsive, we use it to execute a set of Promise asynchronously. The goal is to finish the set of functions as quickly as possible and therefore using an asynchronous method.

The problem with running all the Promises asynchronously is the risk of saturating the browser or the Node.js instance.

To solve this problem, here is a function that will run all the Promises synchronously and minimize the risk of crashing your application. This is valid on the browser side but also on the server side.

const promisesSeries = ps =>
  ps.reduce((p, n) => p.then(n), Promise.resolve());

// Exemple with delay
const delay = d => new Promise(r => setTimeout(r, d));

promisesSeries([() => delay(1000), () => delay(2000)], () => delay(3000)]);

// Waiting 1s + 2s + 3s 
// And execute other code
Related snippets