首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何连锁承诺

如何连锁承诺
EN

Stack Overflow用户
提问于 2016-02-24 19:27:18
回答 2查看 82关注 0票数 0

我有个关于连锁承诺的问题。

这是我的密码:

代码语言:javascript
复制
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);
    })
}

基本上,每次添加或删除产品时,我都需要从myService调用myService方法。这些步骤如下:

代码语言:javascript
复制
Update ID
Remove product if there is a type 'New'
Update ID 
Add product

我该怎么改变这个?谢谢你的帮助!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-02-24 20:01:00

基本上你可以像这样连锁承诺:

代码语言:javascript
复制
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中的输入等等。

票数 1
EN

Stack Overflow用户

发布于 2016-02-24 19:34:57

调用updateID函数,然后从removeProduct返回。如下所示:

代码语言:javascript
复制
$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
          }
        };
      }
    })
  })
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35611245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档