Reputation: 2218
I understand of using of '.then' to chain promises, but the application that I am creating still does not fire in sequence.
dataFactory.getFirst().then(function(resp3){
//handling of resp
console.log('one');
}).then(dataFactory.doSecond(val).then(function(resp) {
//handling of resp
console.log("two");
})).then(dataFactory.getThird().then(function(resp2) {
//handling of resp
console.log("three");
})).then(function(){
$state.go('tab.main'); //goes to main page
});
'dataFactory.' are all my HTTP Post methods invoked in my services.js. I do understand I did not include any exception/failure handling as I re-coded my whole codes(non-promise) to this from scratch. I will add them in once I fixed this problem.
The problem is sometimes, 'getThird()' values will be printed on the console first followed by 'doSecond()'values , which is something that I do not want. Any guidance and suggestions would be deeply appreciated.
Update: Even taking '@Jaromanda X' answers into consideration I'm still unable to achieve sequential chaining. The console is not printing 'one, two, three' in sequence. Is it due to the server response delay?
Updated Code:
var resp; var resp2; var resp3;
(resp3 =dataFactory.getFirst(valone))
.then(function(resp3){
console.log('one');
})
.then(resp = dataFactory.doSecond(val))
.then(function(resp) {
//handling of resp
console.log("two");
})
.then(resp2 = dataFactory.getThird(valtwo))
.then(function(resp2) {
//handling of resp
console.log("three");
}).then(function(){
$state.go('tab.main'); //goes to main page
});
doSecond(val) all functions are similar to this , just different address and different values returned:
dataFactory.doSecond= function(val){
var config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
var data = 'val=' + val;
var httpAddressdoSecond = "http://"+IPAddress+"/webserviceURL";
return $http.post(httpAddressdoSecond, data, config);
};
Upvotes: 0
Views: 99
Reputation: 1
You'll want to do this
dataFactory.getFirst()
.then(function(resp3){
console.log('one');
})
.then(dataFactory.doSecond)
.then(function(resp) {
//handling of resp
console.log("two");
})
.then(dataFactory.getThird)
.then(function(resp2) {
//handling of resp
console.log("three");
}).then(function(){
$state.go('tab.main'); //goes to main page
});
Because the way you're doing it, you're invoking doSecond, getThird immediately, rather as a result of the previous promise resolving
Upvotes: 2