3
\$\begingroup\$

The code below doesn't seem right to me. The scenario is:

  1. User enters in a "quantity" into a form field.
  2. If the user enters in 5, the loop below should iterate 5 times.
  3. There should now be 5 new entries in the database with the container.product and container.status.

Any advice on making this cleaner?

var container = new Container($scope.batchFields);
container.product = $scope.item.originalObject._id;
container.status = 'active';
_.each($scope.batchFields, function(batch) {
 _.each(_.range(batch.batchesQuantity, 0, -1), function (val,i) {
 // This $save code smells a little with it 
 // being inside the _.each.
 container.$save(function(response) {
 $notify.success('purchase.order.edit.created');
 if ($scope.$close) {
 $scope.$close();
 }
 }, function(errorResponse) {
 $scope.errors = errorResponse.data.message;
 });
 });
});
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jul 21, 2015 at 0:52
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Please do not make separate calls (Http requests) for saving each container,as this will affect the web application performance. Instead batch the calls ( 5 calls at one time). Store them in an array and make a single call

_.each($scope.batchFields, function(batch) {
 var containersList = [];
 _.each(_.range(batch.batchesQuantity, 0, -1), function(val, i) {
 // store them in the array
 containersList.push(new Container($scope.batchFields));
 });
 $http.post('saveContainers', containersList).then(function(response) {
 $notify.success('purchase.order.edit.created');
 if ($scope.$close) {
 $scope.$close();
 }
 }, function(errorResponse) {
 $scope.errors = errorResponse.data.message;
 });
});
answered Jul 21, 2015 at 4:15
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.