Reputation: 799
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. 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!
Upvotes: 0
Views: 93
Reputation: 1783
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
. 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.
Upvotes: 1
Reputation: 2326
call the updateID function in the then returned from the 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
}
};
}
})
})
}
Upvotes: 1