javascript - 如何链式 promise

标签 javascript angularjs promise

我有一个关于链式 promise 的问题。

这是我的代码:

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 调用 updateId 方法。所以步骤如下:

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

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

最佳答案

基本上你可以像这样链式 promise :

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 的返回值将是下一个“链”promise then 的输入。在我的例子中,服务函数 pickProduct 必须返回一个保存产品的 promise ,因为我希望它作为 _update 等中的输入。

关于javascript - 如何链式 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35611245/

相关文章:

javascript - 使用 request-promise 嵌套异步请求

javascript - 未捕获的类型错误 : Object #<HTMLDivElement> has no method 'addPanel'

html - 仅使用大写字母的 CSS 或 SASS 选择器

浏览器返回后Javascript清理window.postMessage

javascript - 在 Angularjs 中单击后更改按钮颜色

javascript - 使用finally() 正确构建Javascript Promise

javascript - 带有 promise.prototype.finally 的 Axios 不起作用

javascript - 如何删除 Internet Explorer 中默认文本框中的十字图标

javascript - 如何知道点击了哪个按钮

javascript - 具有不同输入值的 for 循环