2016-02-24 113 views
0

我有一个关于链接承诺的问题。如何链接承诺

这里是我的代码:

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); 
    }) 
} 

基本上我需要调用从myServiceupdateId方法我每次添加一次或删除产品。所以步骤如下:

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

我该如何改变?谢谢您的帮助!

+0

在语句'addProduct(item.id)'中,从哪里获得'item'?或者是一个错字? – georgeawg

+0

有关链接承诺的信息,请参阅[使用'$ q'的角度执行顺序](http://stackoverflow.com/questions/34324153/angular-execution-order-with-q/34326388)。 – georgeawg

回答

1

基本上你可以链的承诺那样:

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) { 

} 

一个then的返回值将成为下一个“链”的承诺then的输入。在我的情况下,服务功能pickProduct必须返回承诺该产品的承诺,因为我期望它在_update等内的输入。

+0

是否有无论如何我可以传递一个额外的参数,没有从以前的承诺返回像你的情况下函数_remove(ID,数据)? +1 – BonJon

+0

嗯,您可以使用闭包,并将_update函数放入您希望的输入所在的函数中,然后通过所有方法调用访问它或拉动param作为输入,并在promise处理程序中返回一个数组。 。 – ChrisY

1

调用removeProduct返回的updateID函数。就像这样:

$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 
      } 
     }; 
     } 
    }) 
    }) 
} 
+0

谢谢。无论如何,我可以做到这一点,而不添加这么多的嵌套然后(功能()?+1 – BonJon