AngularJs Promise sequence

Let’s admit it, we all have a problem with promises and if it wasn’t for this brilliant blog post by Nolan Lawson, I would be trying to figure out why my catch didn’t catch and lets not mention the “deferred” curse.

Now, the final challenge to master promises: Promise Sequence and Promise Factories.

The problem: You need to execute an array of promises i.e. calls to a WebService, however you need to make sure the promises don’t execute in parallel. As we all know, as soon as a promise is created it starts execution. I have combined the solution proposed by Nolan and created an offline data synchronisation example that explains promise factories and excecute the promises in sequence.

Caching webservice calls and creating the factories: 

A Promise factory is a function that returns a promise, in this case I want to save a webservice call to local storage and execute it later. I am using a SOAP Client for AngularJS which already returns a promise:

CreateUser is a function that takes firstName and lastName as parameters and then creates a SOAP call to the server similar to $http methods. $soap.post already returns a promise for us.

We have an array of functions that return promises on our database ready to be executed. Now lets build the promise factory from the records on the Database:

The contents of the variable output are the array of promises we need to execute:

What we have created here could be used to give offline functionality to a mobile application caching any calls made to the server and only deleting them from the list when you get a response. Because your calls execute sequentially, you can be confident that your data is going to be consistent and execute in order it was created by the user.