Sonu Kapoor
Sonu Kapoor

Reputation: 1637

Make http requests in order / series

I built an array with jobs. Jobs are grouped by a start and end transaction. A transaction is a call to the webservice. An entire transaction can look like this:

  1. Create Transaction (calls /opentransaction)
  2. DoSomething A (calls /a)
  3. DoSomething B (calls /b)
  4. etc..
  5. Close Transaction (calls /closetransaction)

My pseudo code looks something like this:

for (var i=0;i<jobs;i++)
{
  $http(job);
}

This works fine, but the order is random. I need to make sure that the order is maintained. How can enforce that?

Upvotes: 0

Views: 1253

Answers (2)

ajmajmajma
ajmajmajma

Reputation: 14216

I don't think looping is a good way of doing this, I would recommend using $q and just iterating through your tasks with a promise.

function myPromiseFunction() {
   return $q(function(resolve, reject) {
       doThingOne
          .then(doThing2)
          .then(doThing3)
          .then(doThing4)
          .then(resolve)
          .catch(function(error) {
               console.log("Error in my promise:", error);
          });
   });
}

The doThing are functions that do each of your desired behaviors so in your case the first thing would create the transaction, and return something to the next function if needed.

Upvotes: 0

Reto Aebersold
Reto Aebersold

Reputation: 16624

Store away the promise of your $http call and let the next job wait until the previous is done. This could look something like this:

var promise = $q.when(true);

for (var i = 0; i < jobs; i++) {
  promise = promise.then(function () {
    return $http(job);
  })
}

Upvotes: 2

Related Questions