While loop with ES6 Promises

It's really great to have promises be part of the standard library in ES6 JavaScript. I've been using them as a part of my scripts long before the ES6 spec was finalized. I was won over as soon as I saw how simple they could be compared to callbacks.

I recently came across an interesting problem. I was calling an API call that was breaking up records into pages. Included in the return object was a "hasNextPage" boolean. From that, I wanted to be able to do another call to retrieve the next set of pages, until there was no data left to get.

In synchronous programming this would be as simple as a while loop. Like most non-trivial problems, it turned out to be a bit trickier when you are doing it asynchronously. I was able to generalize my solution into a sort of while loop. It is a function that takes an initial value, a condition function, and an action function that returns a promise.

const promiseWhile = (data, condition, action) => {  
  var whilst = (data) => {
    return condition(data) ?
      action(data).then(whilst) :
      Promise.resolve(data);
  }
  return whilst(data);
};

This will return a promise that will finish with the condition function returns false.

To see it in action with some simple examples, check out this JSFiddle

Bret Lowrey

Code is like a war - the best code is one never written.

Florida, USA