NoobSter NoobSter - 1 month ago 10
AngularJS Question

Is it bad practice to chain server calls that depend on each other within front end promises?

I'm working with the MEAN stack.

For instance, in my angular code I might have:

Brand.create({name: 'name'}).then(function(brand){

//here, the product's referenced brand._id depends on the Brand response

Product.create({'name':'name', 'category': 'food',
'brand': brand.data._id}).then(function(res){
$scope.product = res.data;
});
});


Would it be better to do this on the server side -- if someone were to refresh or lose connection before the 2nd promise invoked, it seems it could result in only a brand being created -- without an associated product.

If so, would it be a best practice to connect the two different collections within one of their respective controllers?

Answer

Would it be better to do this on the server side -- if someone were to refresh or lose connection before the 2nd promise invoked, it seems it could result in only a brand being created -- without an associated product.

Yes. It would be better done on the server side for a number of reasons:

  1. Fewer Ajax calls over the network is better. So creating a single ajax call that implements the higher level operation you're trying to implement will be more efficient.
  2. The closer your logic and error handling is to the source of the data (e.g. the database), the easier it is to write and execute things reliably.
  3. Your scenario of a lost network connection in the middle of things is a perfect example of a problem with implementing multiple step data operations from the client.

And. No matter where you write the code, you need proper error handling, either via some sort of transaction system in the database or via manual error handling that unwinds prior operations when later ones fail so you always end up with a valid system, even if a middle or later steps fails. In your client-driven scenario above, you need a .catch() handler on Produce.create() so if that fails, you can undo the Band.create() from previously so you leave the system in a proper state if you have a downstream error. Note, this is next to impossible in the face of client connectivity issues if you manage multiple steps from the client, but much more practical when done from the server where you are significantly less likely to have connection issues.