[英]How to chain promise
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. 基本上,每次添加或删除产品时,都需要从myService
调用updateId
方法。 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! 谢谢您的帮助!
call the updateID function in the then returned from the removeProduct. 调用updateID函数,然后从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
}
};
}
})
})
}
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
. 的返回值then
将是下一个“链”承诺的输入then
。 In my case the service function pickProduct
has to return a promise that holds the product, because I expect it as input within _update
and so on. 在我的情况下,服务函数pickProduct
必须返回一个保存该产品的_update
,因为我希望它作为_update
等中的输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.