I have been doing lots of searching trying to find a solution, and believe it ultimately comes down the the promise as my data is returned but all at the end, where as I need it through each iteration.
I have the vm.planWeek.dinner that I loop through each row, and append 'menuType' and the 'trackMenuIds' array to it, which I then use in my MongoDB call for search criteria. This all works fine, but the key element, is with each factory call returned, I add the returned item's id to the 'trackMenuIds' array. The reason for this is, it builds an array of items I already have returned, so they can ignored in the next call, ie via $nin.
vm.reviewWeek = function () {
//Array to be updated over each iteration and used in factory call
var trackMenuIds = [];
angular.forEach(vm.planWeek.dinner, function (day) {
//Adds two more items to day(current row) to pass to factory
day.menuType = 'dinner';
day.weekIds = trackMenuIds;
//Factory call - each time this runs, the 'trackMenuIds' array should have
//one more item added from the previous run
menuFactory.matchMenuCriteria(day)
.then(function (response) {
var randomItem = response.data[0];
day.menuItem = {'_id': randomItem._id, 'name': randomItem.name};
//adds the current id to the array to be used for the next run
trackMenuIds.push(randomItem._id);
});
});
};
When I append the 'trackMenuIds' array to the current row, it hasn't been updated with any id's. When I console it, I can see it does infact add them, but believe as its part of a promise, it is not doing it early enough to pass the updated array into my factory call over each iteration.
I have tried chain promises and other means but just can't seem to get it to work. Quite possibly it comes down to my inexperience of promises, so any help would be greatly appreciated.
The calls to the factory asynchronous API are being made in parallel. They need to chained sequentially:
vm.reviewWeek = function () {
//Array to be updated over each iteration and used in factory call
var trackMenuIds = [];
//INITIAL empty promise
var promise = $q.when();
angular.forEach(vm.planWeek.dinner, function (day) {
//Adds two more items to day(current row) to pass to factory
day.menuType = 'dinner';
day.weekIds = trackMenuIds;
//Factory call - each time this runs, the 'trackMenuIds' array should have
//one more item added from the previous run
//CHAIN sequentially
promise = promise.then(function () {
//RETURN API promise to chain
return menuFactory.matchMenuCriteria(day);
}).then(function (response) {
var randomItem = response.data[0];
day.menuItem = {'_id': randomItem._id, 'name': randomItem.name};
//adds the current id to the array to be used for the next run
trackMenuIds.push(randomItem._id);
});
});
return promise;
};
The above example creates an initial empty promise. The foreach loop then chains a call to the asynchronous API on each iteration.
You can use $q.all to handle multiple asynchronous call. Once all promise done execute, loop through raw Http promise and then push the data to the new array
vm.reviewWeek = function () {
//Array to be updated over each iteration and used in factory call
var trackMenuIds = [];
var dinnersPromise = [];
vm.planWeek.dinner.forEach(function (day, ind) {
//Adds two more items to day(current row) to pass to factory
day.menuType = 'dinner';
day.weekIds = trackMenuIds;
dinnersPromise.push(menuFactory.matchMenuCriteria(day));
});
$q.all(dinnersPromise).then(function (arr) {
angular.forEach(arr, function (response) {
var randomItem = response.data[0];
day.menuItem = {'_id': randomItem._id, 'name': randomItem.name};
//adds the current id to the array to be used for the next run
trackMenuIds.push(randomItem._id);
});
});
}
Related
What am i trying to achieve is as such:
Invoking my service to retrieve all appointments in appointment types (number of types not fixed) tied to a doctor
If there are 3 appointment types, then there will be 3 async calls made
return a single promise with $q.all() after all 3 promises have been resolved
appointmentService
this.getAllDoctorAppointments = function (doctor, appointmentTypeArray) {
var promises = [];
angular.forEach(appointmentTypeArray, function (appointmentType) {
var defer = $q.defer();
$http.get('/appointments/?doctorName=' + doctor + '&apptType=' + appointmentType)
.success(function (listOfAppointments) {
defer.resolve(listOfAppointments);
promises.push(defer.promise);
});
});
return $q.all(promises);
};
In my console log, the appointmentType returns [ ].
This happens because the empty 'promises' array is returned even before the 3 async calls are made. I am still very new to the concept of promises, what is the best approach to work this out? Thanks!
$scope.getAllDoctorAppointments = function (doctor, appointmentTypeArray) {
appointmentService.getAllDoctorAppointments(doctor, appointmentTypeArray)
.then(function (appointmentType) {
//could take in any number. hardcoded 3 just for testing.
console.log(appointmentType)
angular.forEach(appointmentType[0], function (xRay) {
$scope.xRayAppts.events.push(xRay);
});
angular.forEach(appointmentType[1], function (ctScan) {
$scope.ctScanAppts.events.push(ctScan);
});
angular.forEach(appointmentType[2], function (mri) {
$scope.mriAppts.events.push(mri);
});
});
};
this.getAllDoctorAppointments = function (doctor, appointmentTypeArray) {
var promises = [];
angular.forEach(appointmentTypeArray, function (appointmentType) {
promises.push($http.get('/appointments/?doctorName=' + doctor + '&apptType=' + appointmentType)
.success(function (listOfAppointments) {
return listOfAppointments;
});
);
});
return $q.all(promises);
};
$http.get returns the promises that you wants to collect, there is no need for a new defer in this case.
the promise is not being added to the array because the code that adds it to the array, promises.push(defer.promise);, is inside of the result code of the thing you are trying to defer. So the promise wouldn't get added to the list of promises to execute until after it executed!
so you can either move that push line outside of the success call looking something like this:
angular.forEach(appointmentTypeArray, function (appointmentType) {
var defer = $q.defer();
$http.get('/appointments/?doctorName=' + doctor + '&apptType=' + appointmentType)
.success(function (listOfAppointments) {
defer.resolve(listOfAppointments);
});
promises.push(defer.promise);
});
or, you can do as lcycool suggests and just add the $http.get(...).success(...) calls to the array directly.
I am struggling with this for a while, and can't figure it out. What I have is main controller, factory, and service, and I'm trying to store array from service to $scope in controller. On view on item click this function in controller is triggered:
$scope.getSongsInPlaylist = function()
{
var playlistId = this.item.idPlayliste;
$scope.Mp3Files = songInPlaylistFactory.getSongsForPlaylist(playlistId);
}
That works ok, this function retrieves item from view and sends id of that item to function in service.
Than in my service I have code like this:
var Songs = [ ];
this.getSongsForPlaylist = function (id)
{
for (var i = 0; i < SongIsOnPlaylist.length; i++)
{
if(SongIsOnPlaylist[i].idPlayliste == id)
{
dataFactory.getDataById(mp3fileUrl, SongIsOnPlaylist[i].idPjesme)
.success(function (data) {
Songs.push(data);
alert(Songs[0].naslovPjesme);//Alert one
});
}
}
alert(Songs[0]);// Alert two
return Songs;
}
dataFactory is my factory that communicates with api in backend, and that works too. var Songs is defined as: var Songs = [ ]; And SongIsOnPlaylist is filled with data.
When I trigger this, alert two gives me undefined, and alert one gives me name of first song in Songs. That means var Songs is filled with data, but when I want it to return to controller its empty ...
Am I doing something wrong here, I would appreciate any help?
First it looks like your dataFactory.getDataById is async call.
Because of this what is actually happening is you returns an empty Songs array before it gets populated when all your async calls returns.
To solve this I would advise to use a Promise library like bluebird to do something like this:
// note that now your service will return a promise
this.getSongsForPlaylist = function (id) {
return new Promise(function(resolve, reject) {
var promises = [];
// here in your loop just populate an array with your promises
for (var i = 0; i < SongIsOnPlaylist.length; i++){
if(SongIsOnPlaylist[i].idPlayliste == id){
promises.push( dataFactory.getDataById(mp3fileUrl, SongIsOnPlaylist[i].idPjesme) )
}
}
// now use the library to resolve all promises
Promise.all(promises).then( function (results) {
//HERE YOU WILL GET the results off all your async calls
// parse the results
// prepare the array with songs
// and call
resolve(Songs);
});
});
}
Then you will use the service like this:
$scope.getSongsInPlaylist = function() {
var playlistId = this.item.idPlayliste;
songInPlaylistFactory.getSongsForPlaylist(playlistId)
.then(function(Songs){
$scope.Mp3Files = Songs
})
.error(function(err){
//here handle any error
});
}
Im trying to iterate over an array that I construct from multiple http calls inside a angular.forEach()
the function
$scope.ticket_stats = function(){
//cleaning variables
$scope.data_set = [];
$scope.closed_tickets = [];
//fetching time stamps (epoch)
$scope.time_frame = time_period.days(7);
//calling data using time stamps
angular.forEach($scope.time_frame, function(item) {
//debug
console.log(item);
var promise = tickets.status("closed", item);
promise.success(function(data){
console.log(data);
$scope.closed_tickets.push(data[0].datapoints[0][0]); // returns a numerical value
});
});
//SEE MESSAGE BELOW
$scope.data_set.push($scope.closed_tickets);
}
the last line $scope.data_set.push() is working but increment itself over time once calls return data. I would like this line to be executed once everything within the for Each loop is all done. I need to iterate over the $scope.closed_tickets array afteward to play (addition) data inside it and build up a second array.
here are the services used in this function:
// CALL TICKETS STATS
app.service('tickets', function($http){
this.status = function(status, date){
var one_snap = date - 100;
var url = "/url/render?format=json&target=sum(stats.tickets."+status+")&from="+one_snap+"&until="+date+"";
return $http.get(url);
};
});
// TIME STAMPS MATHS
app.service('time_period', function(){
var currentDate = parseInt((new Date).getTime()/1000);
this.days = function(number){
var pending = [];
for (var i = number; i > 0; i--) {
pending.push(currentDate - (87677*i));
}
return pending;
};
});
I search for information and found out about the $q.all() service but didn't manage to make this work the way I want.
Any advices would be welcomed!
Thanks!
You can use $q.all to wait for multiple ansynchronous events (promises) to finish.
$scope.ticket_stats = function() {
// list of all promises
var promises = [];
//cleaning variables
$scope.data_set = [];
$scope.closed_tickets = [];
//fetching time stamps (epoch)
$scope.time_frame = time_period.days(7);
//calling data using time stamps
angular.forEach($scope.time_frame, function(item) {
// create a $q deferred promise
var deferred = $q.defer();
//debug
console.log(item);
tickets.status("closed", item).success(function(data) {
console.log(data);
$scope.closed_tickets.push(data[0].datapoints[0][0]);
// promise successfully resolved
deferred.resolve(data);
});
// add to the list of promises
promises.push(deferred.promise);
});
// execute all the promises and do something with the results
$q.all(promises).then(
// success
// results: an array of data objects from each deferred.resolve(data) call
function(results) {
$scope.data_set.push($scope.closed_tickets);
},
// error
function(response) {
}
);
}
First, deferred represents a piece of code that will take an unknown amount of time to execute (asynchronous). deferred.resolve(data) simply states that the code is finished. Data could be anything, an object, string, whatever, but it is usually the results of your asynchronous code. Likewise you can reject a promise with deferred.reject(data) (maybe an error was thrown by the sever). Again, data can be anything but here it should probably be the error response.
deferred.promise just returns a promise object. The promise object allows you to set callbacks like .then(successFunction, errorFunction) so you know a piece of code has finished executing before moving on to successFunction (or errorFunction in the case of a failure). In our case $q has the .all method which waits for an array of promises to finish then gives you the results of all the promises as an array.
Don't forget to inject the $q service.
Try to make an array of promises only, without resolving them yet. Then aggregate them with $q.all(). After aggregated promise resolve iterate through the array of those promises again. Now you are sure that they are all resolved.
var promises = [];
angular.forEach($scope.time_frame, function(item) {
promises.push(tickets.status("closed", item));
});
var aggregatedPromise = $q.all(promises);
aggregatedPromise.success(function(){
angular.forEach(promises, function(promise) {
promise.success(function(data){
$scope.closed_tickets.push(data[0].datapoints[0][0]); // returns a numerical value
});
});
});
Maybe this is not the most efficient way to do this, but I think that should solve your problem.
Even though you mention $q.all didn't work for you, as I don't see why it should't, here's how I would do this.
Basically you want to map an array of things (time stamps) to some other things (promises in this case since we have async calls) and do some action on the resulting array.
var promises = $scope.time_frame.map(function (item) {
return tickets.status("closed", item);
});
Now we use $q.all to wait for all promises to resolve:
$q.all(promises).then(function (tickets) {
$scope.data_set.push(tickets);
});
I am making calls to two different firebase locations to get the data, once the data is $loaded, I am creating one object. then push this objects into one array and returning array.
But I am not getting array that is been return from factory
myApp.factory('MybetFactory', ['$firebase', function ($firebase) {
var factory = {};
factory.getUsersBetsProfile = function (userId, callback) {
//1. first call to firebase data
var firebaseUsersBetsProfileRef = new Firebase("https://x.firebaseio.com/profile").child(userId);
var userBettedEvent = [];
var userBetProfile = $firebase(firebaseUsersBetsProfileRef).$asObject();
//2. once object is loaded call second location and load the data
userBetProfile.$loaded().then(function () {
angular.forEach(userBetProfile, function (eachUserBetProfile) {
if (eachUserBetProfile !== null && eachUserBetProfile.hasOwnProperty('id')) {
var firebaseEventsResultsRef = new Firebase("https://x.firebaseio.com/result/+id");
var resultsForProfileBets = $firebase(firebaseEventsResultsRef).$asObject();
//3. once the data is loaded, push it into object created above
resultsForProfileBets.$loaded().then(function () {
console.log('Results for profile bets loaded', resultsForProfileBets);
eachUserBetProfile.results = resultsForProfileBets;
//4. push same object in array
userBettedEvent.push(eachUserBetProfile);
});
}
});
});
//Issue: this array is not been return in scope
return userBettedEvent;
};
return factory;
}]);
The reason that your array isn't visible on your return userBettedEvent line is because of how callbacks work in JavaScript.
Callbacks, which are things that look like this,
doSomethingCool("stuff", function() {...});
usually run once the function they're passed to completes. While your browser waits for doSomethingCool to finish, it goes on executing the subsequent code.
In other words, if you have code like this:
doSomethingCool("stuff", function() {
console.log("hello");
});
console.log("goodbye");
you're probably going to see this output:
goodbye
hello
To resolve your issue, you need to understand how callbacks work in JavaScript.
$scope.iter = 0;
$scope.myArray.forEach(function () {
$http.get($scope.myArray[$scope.iter].URL)
.success(function (data) {
$scope.myArray2.push(data);
//$scope.myArray2[$scope.iter]=data
});
$scope.iter++;
})
The above code works but I want the results in myArray2 in the same order as it was called. I know that I cannot expect $scope.myArray2[$scope.iter]=data to work but that is what I need.
I looked at the angular documentation on promises but could not make out how to use it for the above.
You can put all promises from the get requests in an array and use $q.all() to create a promise that resolves when all underlying promises resolve. You can then iterate the responses in the order they were added to the requests array, and push each response's data into the array in order...
function controller ($scope, $q) {
// ...
var requests = [];
var $scope.myArray2 = [];
angular.forEach($scope.myArray, function (value) {
requests.push($http.get(value.URL));
});
$q.all(requests).then(function(results) {
angular.forEach(results, function(result) {
$scope.myArray2.push(result.data);
});
});
}
Dont understand what you are trying to achieve, but here is an example of simple deferred promises in a controller:
var firstDefer= $q.defer();
firstDefer.promise.then(function(thing){
// here you make the first request,
// only when the first request is completed
//the variable that you return will be filled and
//returned. The thing that you return in the first .then
// is the parameter that you receive in the second .then
return thingPlusRequestData;
}).then(function(thingPlusRequestData){
//second request
return thingPlusPlusRequestData;
}).then(function(thingPlusPlusRequestData){
//and so on...
});
firstDefer.resolve(thing);
//when you call .resolve it tries to "accomplish" the first promise
//you can pass something if you want as a parameter and it will be
// the first .then parameter.
Hope this helps u :D
You will normally NOT get the results in the order you called the $http.get(...) function. Mind that the success(...) function is called asynchronously, whenever the http response comes in, and the order of those responses is totaly unpredictable.
However you can work around this by waiting for all the responses to finish, and then sort them according to your criteria.
Here is the working fiddle: http://fiddle.jshell.net/3C8R3/3/