0

I have a question regarding chaining promise.

Here's my code:

var removeProducts = function(id) {
    anotherService.removeProducts(id); // this will return a promise.
}

var addProduct = function(id) {
    myService.addProduct({id: id})
}

$scope.pickProduct = function() {
    myService.updateId({'id':123}).$promise.then(function(items) {
        items.categories.filter(function(category) {
            if (category.type === 'NEW') {
               removeProducts(items.id);
            }
        })
        //this is the part I don't know how to proceed. I need to make sure 
        //the product is removed before first and update ID second so I can add     
        //another product.  

        addProduct(item.id);
    })
}

Basically I need to call the updateId method from myService every time I add or remove a product. So the steps are as follows:

Update ID
Remove product if there is a type 'New'
Update ID 
Add product

How do I change this? Thanks for the help!

Seth
  • 10,198
  • 10
  • 45
  • 68
BonJon
  • 779
  • 1
  • 7
  • 21
  • In the statement `addProduct(item.id)`, from where do you get `item`? Or is that a typo? – georgeawg Feb 25 '16 at 00:44
  • For information on chaining promises, see [Angular execution order with `$q`](http://stackoverflow.com/questions/34324153/angular-execution-order-with-q/34326388). – georgeawg Feb 25 '16 at 00:47

2 Answers2

1

call the updateID function in the then returned from the removeProduct. Like this:

$scope.pickProduct = function() {
  myService.updateId({
    'id': 123
  }).$promise.then(function(items) {
    items.categories.filter(function(category) {
      if (category.type === 'NEW') {
        removeProducts(items.id).then(function() {
            //call updateId .then(function(){
            // call add product
          }
        };
      }
    })
  })
}
Seth
  • 10,198
  • 10
  • 45
  • 68
M B
  • 2,326
  • 24
  • 33
1

Basically you can chain promise like that:

myService.pickProduct(product)
    .then(_update)
    .then(_remove)
    .then(_add)
    .catch(..);



function _update(product) {
    return product.id;
}

function _remove(id) {
   return new Date();
}

function _add(date) {

}

The return value of a then will be the input of the next 'chain' promise then. In my case the service function pickProducthas to return a promise that holds the product, because I expect it as input within _updateand so on.

ChrisY
  • 1,681
  • 10
  • 12
  • is there anyway I can pass an additional param that didn't return from the previous promise like function _remove(id, data) in your case? +1 – BonJon Feb 24 '16 at 20:13
  • Hmm. You could use a closure for that and put the _update function into the function where your desired input lives and then just access it or pull the param through all method call as an input and return an array within the promise handlers.. – ChrisY Feb 24 '16 at 20:19