Create controlled async sequences

Today I’ve been asked on how approach the creation of a sequence of async calls and retain control over any possible point of failure.
There are several possible solutions to this scenario, using es2016’s async functions or es2015’s generator functions would make the solution simpler and easier to be read but I’ve been asked to use only valid es5 code.

The goals of this particular exercise are:

  • accept sequences of variable length
  • create a reusable solution
  • have knowledge and control over thrown exceptions

The basic idea is to create an array of async actions and execute it step by step. To support this we need an object able to iterate over our array of actions.

createAsyncSequence() returns our iterator function. Passing an array to the iterator starts the async sequence.
Every actions must implement a simple definition object used to specify handler methods for failure and success.

This is the full code of the iterator:

This version passes all values returned from the previous steps to every async function executed. The asynchronous executor could use this values.
The iterator can be augmented with default handlers to ease in the sequences creation.

Here you can play with a complete example:

open in jsbin
ABCD

You can also see the initial version, made with AngularJS.