Run asynchronous functions in series with ES6

I was stuck on a problem where I was struggling with getting an array of callback taking functions to run in sequence. I didn't want to bring in external dependencies such as async. In the end I stumbled across this post http://stackoverflow.com/questions/29880715/how-to-synchronize-a-sequence-of-promises#answer-29906506. This pointed me in the right direction here and this was how I implemented it:

function delegate(...hooks) {  
  return (nextState, replaceState, callback) => {

    function runHook(hook) {
      return new Promise((resolve) => {
        hook(nextState, replaceState, () => {
          resolve();
        });
      });
    }

    let index = 0;
    function next() {
      if (index < hooks.length) {
        runHook(hooks[index++]).then(next);
      } else {
        callback();
      }
    }
    next();
  };
}

So simple if you only set up the cascade as you run it instead of building a huge complex web of promises.

Rudi Yardley

Read more posts by this author.