我有一个关于链式 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/