Reputation: 5826
I am implementing multiple ajax calls in sequence in angular. What I want to achieve is working fine with $.ajax
but when I implemented with angular where I'm using $http
for server request, it's not working. I am wondering that both are returning promise object then why it's not working properly.
Using $.ajax
shoppingList.split(",").reduce(function(resultPromise, shoppingItem) {
return resultPromise.then(function(result) {
pro = $.ajax('/items/'+shoppingItem);
return pro.then(function(res) {
console.log(result);
result.push(new Item(res.label,res.price));
return result;
});
});
}, $.when([])).then(completeCallback);
See the working fiddle - JSFiddle
Using Angular $http
function fetchDataDayWise(dateRanges,completeCallback) {
return dateRanges.reduce(function(resultPromise, dt) {
return resultPromise.then(function(resultData) {
machinePromise = getData();
return machinePromise.then(function(data) {
if(data && data.length > 0)
{
resultData = resultData.concat(data);
}
console.log(resultData);
return resultData;
});
});
}, $.when([])).then(completeCallback);
}
var dateRanges = [1,2,3,4]
function setData(data) {
console.log("data",arguments);
}
fetchDataDayWise(dateRanges,setData);
See the Plunkr
You can see in console. In JSFiddle, you will get array of items while in Angular plunkr it returns object. I guess it's promise object.
Any help would be appreciated.
Upvotes: 0
Views: 342
Reputation: 121
In your service you use $http.get, this returns a promise which is the object you are seeing, to get your values from it you need to have (in your case):
deferred.resolve(data.data);
instead of
deferred.resolve(data);
Hope this helps. If you have any more questions i'll be happy to answer them.
Update:
This isn't for your code exactly, but it will give you an example of how to achieve sequential calls.
var prevPromise = $q.resolve();
prevPromise = prevPromise.then(function() {
this.someValue= value; //array of databases containing queryresults
return this.function(req, res);
}.bind(this));
Upvotes: 1
Reputation: 4713
I have forked your plnkr hope this will help
http://plnkr.co/edit/VWJMNU?p=preview
function fetchDataDayWise(dateRanges, compleCallback) {
var arrPromise = [];
dateRanges.reduce(function (dt) {
arrPromise.push(getData());
});
$q.all(arrPromise).then(compleCallback);
}
Upvotes: 0