Recursive JavaScript Promises!

ES6 promises give JavaScript the flexibility and code readability needed to become a more powerful development tool.  However, Promises are not necessarily easy to follow if you’re used to procedural code.  Add to this the concept of recursion and your head may start to hurt!

The following example shows how an asynchronous function can call itself using promises which eventually all resolve up the chain when the final condition is met.

// pause function to return after specified milliseconds
pause = (ms) => new Promise(resolve => {
  setTimeout(resolve, ms);
});

// recursive function which resolves after all iterations
recursePromises = (total, index) => new Promise(resolve => {

  // initialise index if undefined
  index = index || 0;

  if (index < total) {
    console.log(index);
    pause(500)
      .then(() => {
        return recursePromises(total, ++index);
      })
      .then(resolve);
  } else {
    resolve('Done ' + index + ' iterations!');
  }
});

Calling the function thusly:

recursePromises(15)
  .then(res => {
    console.log(res);
  });

will produce the result:

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Done 15 iterations!

Hereby we can iterate an asynchronous set of operations and be sure all are completed when the calling promise function has resolved.

Nice.

Leave a Reply

Your e-mail address will not be published. Required fields are marked *