Making asynchronous calls sequentially in JavaScript/TypeScript

I recently needed to perform a number of asynchronous actions in sequence, i.e. I didn’t want the nth action to be executed until the nth-1 action was completed.

The first thing I did was to implement a function called fold that’s commonly used in functional programming to reduce a list into a single value:

It’s easier to see with the TypeScript type annotations exactly what’s going on. The function takes an array of items, an initial value that’s a seed for the accumulated value and a function that takes the accumulated value and the next value in the sequence to produce the new accumulated value. The initial value needs to be carefully considered so that you get the expected outcome – for example using fold to add numbers:

Here 0 is the initial value because the first value added to 0 will simply be the first value (effectively the identity function). Compare this with multiplication:

Here 1 is the initial value because the first value multiplied by 1 will be the first value.

Using fold we can then take an array of functions that produce promises (which JQuery’s Deferreds implement) and combine them to return a promise that is resolved when the last of the actions is completed:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s