I set up a function in my service to return a list of servers/hosts that are related to a certain application. For front end purposes I have been trying to assign the host a color depending on how many services on that host are running okay/warning/critical. To implement this I am first doing an api call to get all the hosts related to that application and then I loop through the returned hostlist and do another api call to get services.
My issue is that they are resolving in the correct order so my Data2 variable is returning "undefined". How do I get it to resolve within the first for loop so I can assign a status color to each host?
Is there a better way to implement this?
Here is the function I have defined in my service.
// Function to get Servers and all their information **********************************
service.getHosts = function(AppName){
var HostList = [];
//intial http call to get the correct hostlist associated with the selected application ************
var promise = $http.get('http://localhost:9000/App/' + AppName);
promise.then(function(response){
var Data = response.data.recordset;
//Looping through each host is the recordset to push them into the HostList[] **********************
for (i = 0; i <= Data.length -1; i++){
//variables for the loop
var StatusColor = '';
var StatusTextColor = '';
var count = 0;
//another http call to get the services for each host in the Hostlist ******************************
$http.get('http://localhost:9000/Service/' + Data[i].HostName)
.then(function(response){
var Data2 = response.recordset;
//looping through the services to see if any of the services have status other than ok (shortstatus != 0) ********
for(i = 0; i<= Data2.length-1; i++){
if(Data2[i].ShortStatus != 0){
count = count + 1;
}
}
//Assigning the status color for each host depending on how many services are not ok (either warning or critical) *************
if (count == 0){
StatusColor ='rgb(255,152,0)';
StatusTextColor = 'black';
}else if (count == 1){
StatusColor ='rgb(255,152,0)';
StatusTextColor = 'white';
}else{
StatusColor = 'rgb(244,67,54)';
StatusTextColor = 'white';
}
//Pushing host information and status color to the HostList **********************
HostList.push({
"address":Data[i].Address,
"hostname":Data[i].HostName.split('.')[0],
"fullhostname":Data[i].HostName,
"statuscolor":StatusColor,
// "textcolor":'black'
})
});
}
})
return HostList;
};
Any help is greatly appreciated or any suggests of a simpler or more elegant way would be awesome.
Use $q.all and promise chaining
service.getHosts = function (AppName) {
//returns a http promise
return $http.get('http://localhost:9000/App/' + AppName)
.then(function (response) {
var Data = response.data.recordset;
//makes an array of $http promises
var promises = Data.map(function (dt) {
return $http.get('http://localhost:9000/Service/' + dt.HostName)
});
//executes all the promises in the array simultaneously and returns a single promise object
//whose result(response.data) will be an array of all the responses from the promises in the array
return $q.all(promises);
})
};
//Call the service method
service.getHosts("app_name_here")
.then(function(response){
//response.data will have an array of responses for all the inner $http.get calls
//you wont still be able to return the data because everything is asynchronous
//Populate your data in the $scope here after data massaging
})
Promises can be chained by using a return statement:
$http.get(url).then(function(response) {
return $http.get(url2);
}).then(function(response2) {
return $http.get(url3);
}).then(function(response3) {
//...
});
For more information, see
AngularJS $q Service API Reference - Chaining Promises
You're Missing the Point of Promises
Related
I've been looking and looking everywhere for an example of how to get this to work appropriately. I've tried using $q.all() and it doesn't work. I can't seem to get promises to work appropriately or I'm not accessing them correctly. I'm making an API call to retrieve information about movies and I want to keep them ordered by release date. The easiest way would be to keep the call in the order I make them. I order the movie ids by release date and call them in that array order. Then I want to push the data from the call to a new array. But it's instead not always doing it in the correct order. Could someone possibly tell me what I may be doing wrong?
$scope.movies = [
{url:"tt3470600", group:"m",youtube:"Vso5o11LuGU", showtimes: "times1"},
{url:"tt3521164", group:"m",youtube:"iAmI1ExVqt4", showtimes: "times2"}
];
$scope.imdb = function () {
var promises = [];
for(var i = 0; i < $scope.movies.length; i++) {
var movie = $scope.movies[i];
var options = {trailer: movie.youtube, times: $scope.times[movie.showtimes]};
var promise = $http.get('http://www.omdbapi.com/?i=' + movie.url);
promise.times = options;
promises.push(promise);
};
return $q.all(promises);
};
var x = $scope.imdb();
console.log(x);
What's returned is an object d with a key of $$state. I would love to keep the order desperately because the times I return have a date selection that I would like to keep ordered.
I think you just missed something important here which is
var deferred = q.defer(); //init promise
and also
deferred.resolve(item); // resolve the promise
besides that
don't forget to handle error cases -> use deferred.reject(item) for those
Once you have done with all your promise, save all the results into the array
var arr = [];
q.allSettled(promises).then(function(results) {
arr = results;
});
You can use $q in a func to return a promise and make the http call inside that function and then call this based on the order you desire to get the array of promises.
var ajaxcallURl = {
0: 'https://api.github.com/users?since=84',
1: 'https://api.github.com/search/users?q=tyler',
2: 'https://api.github.com/users?since=357',
3: 'https://api.github.com/users?since=19990',
4: 'https://api.github.com/search/users?q=john',
5: 'https://api.github.com/users?since=2345',
6: 'https://api.github.com/users?since=1899',
7: 'https://api.github.com/search/users?q=james',
8: 'https://api.github.com/users?since=786',
9: 'https://api.github.com/search/users?q=nicholas',
10: 'https://api.github.com/users?since=99'
}
var SomeAsyncCall = function () {
var status_deferred = $q.defer();
var requestUrl = ajaxcallURl[count];
$http.get(requestUrl).
success(function (data, status, headers, config) {
status_deferred.resolve(data);
}).error(function (errdata, status, header, config) {
//requestData call failed, pass additional data with the reject call if needed
status_deferred.reject(errdata);
});
return status_deferred.promise;
}
With this promise array you can use $q.all to resolve all those and get the results when all those promises are done.
function createPromisesArray() {
var promiseArray = [];
for (var i=0;i<10;i++){
promiseArray.push(SomeAsyncCall());
}
return promiseArray;
}
var lstPromised = createPromisesArray();
$q.all(lstPromised).then((values) => {
console.log(values[0]);
console.log(values[1]);
// ....
console.log(values[9]);
values.forEach(function (result) {
console.log(result)
});
even though $q.all executes all promises asynchronously , you can get the appropriate promise result from the array.
I have a function inside a service that makes $http.get request from an array
var ids = [1,2,3]
var extensionPromises = [];
for (var i = 0 ; i < extensions.length ; i++) {
var myPromise = myHttpService.getOneExtension(ids[i]);
extensionPromises.push(myPromise);
}
return $q.when(
Promise.all(extensionPromises).then(function(all){
$rootScope.$broadcast("allReady");
return true;
}).catch(function(error){
var e = {};
e.error = error;
e.error.type = "http.get";
return (e);
})
);
That send the ID to a simple $http.get( myUrl + id).then()..., all work ok but when I see the XHR get info in the console, it resolves in the inverse order, that is 3, 2, 1.
Is this normal?
There are no guarantees on order of resolve of multiple async requests. They are subject to network time, server time etc. Even 2 requests to same endpoint may not return in same order they were sent
I have these ngResource queries in my controller:
Ages.query(function(ages){
$scope.ages = ages;
});
Skinissues.query(function(skinissues){
$scope.skinissues = skinissues;
});
Skintypes.query(function(skintypes){
$scope.skintypes = skintypes;
});
Activities.query(function(activities){
$scope.activities = activities;
});
In the same controller in findOne function:
$scope.findOne = function() {
Products.get({
productId: $routeParams.productId
}, function(product) {
for (var i = 0; i < product.ages.length; i ++){
for (var j = 0; j < $scope.ages.length; j ++){
if (product.ages[i].id == $scope.ages[j].id){
$scope.ages[j]['ticked'] = true;
}
}
}
for (var i = 0; i < product.activities.length; i ++){
for (var j = 0; j < $scope.activities.length; j ++){
if (product.activities[i].id == $scope.activities[j].id){
$scope.activities[i]['ticked'] = true;
}
}
}
for (var i = 0; i < product.skintypes.length; i ++){
for (var j = 0; j < $scope.skintypes.length; j ++){
if (product.skintypes[i].id == $scope.skintypes[j].id){
$scope.skintypes[i]['ticked'] = true;
}
}
}
for (var i = 0; i < product.skinissues.length; i ++){
for (var j = 0; j < $scope.skinissues.length; j ++){
if (product.skinissues[i].id == $scope.skinissues[j].id){
$scope.skinissues[i]['ticked'] = true;
}
}
}
for (var i = 0; i < $scope.parents.length; i ++){
if ($scope.parents[i].id == product.parent.id){
$scope.parents[i]['ticked'] = true;
}
}
console.log('Products', product);
$scope.product = product;
});
};
This code, sometimes, it works, sometimes it doesn't, because in the findOne function, sometimes, the $scope.ages $scope.skinissues $scope.skintypes or $scope.activities is undefined.
This happens because their queries haven't finished yet.
What can I do to solve this problem?
Please help. Thanks.
Use $q.all to resolve the $resource promises.
angular.module('mean.variables')
.factory('Variables', function($q, Products, Ages, Activities, Skinissues, Skintypes, _){
return {
get: function(){
var promiseHash = {};
promiseHash.ages = Ages.query().$promise;
promiseHash.skinissues = Skinissues.query().$promise;
promiseHash.skintypes = Skintypes.query().$promise;
promiseHash.activities = Activities.query().$promise;
promiseHash.parents = Products.query().$promise;
return $q.all(promiseHash);
}
}
});
The above example function returns a promise that either resolves sucessfully to a hash of the query objects or resolves rejected with the first rejected response object.
The advantage of using $q.all() instead of $q.defer is that the promise chains aren't broken and error responses are retained for clients of the factory.
From the Docs:
The Resource instances and collections have these additional properties:
$promise: the promise of the original server interaction that created this instance or collection.
On success, the promise is resolved with the same resource instance or collection object, updated with data from server. This makes it easy to use in resolve section of $routeProvider.when() to defer view rendering until the resource(s) are loaded.
On failure, the promise is rejected with the http response object, without the resource property.
If an interceptor object was provided, the promise will instead be resolved with the value returned by the interceptor.
--AngularJS ngResource API Reference
all(promises);
Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.
Parameters
An array or hash of promises.
Returns
Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value.
--AngularJS $q Service API Reference -- $q.all
Thanks guy, I've came up with this service by using setInterval to check if all variable are defined.
angular.module('mean.variables')
.factory('Variables', ['$q', 'Products', 'Ages', 'Activities', 'Skinissues', 'Skintypes', '_', function($q, Products, Ages, Activities, Skinissues, Skintypes, _){
return {
get: function(){
var variables = {};
var defer = $q.defer();
Ages.query(function(res){
variables.ages = res;
});
Skinissues.query(function(res){
variables.skinissues = res;
});
Skintypes.query(function(res){
variables.skintypes = res;
});
Activities.query(function(res){
variables.activities = res;
});
Products.query(function(res){
variables.parents = res;
});
var timer = setInterval(function(){
if (variables.ages && variables.activities && variables.skinissues && variables.skintypes && variables.parents){
defer.resolve(variables);
clearInterval(timer);
}
}, 50);
return defer.promise;
}
}
}])
I am working on a promise chain. The first call is an $http call to check if a user exists, and then if it does, theres a bunch of .then() statements that run sequentially.
My question is this.. in that first call, i don't want to return the promise of the $http request because if the user doesn't exist, the results are just an empty array and the promise resolves, thus triggering the next action to look up information about the user. I wrote the following code...
(see the part in comments about being the important part i'm asking about)
$scope.checkIfUserExists = function() {
if (angular.isObject($scope.admin.Inductee.Contactor)) {
var handleFault = function( fault ) {
if (typeof(fault) === 'string') {
switch (fault.toUpperCase()){
case 'NODATA':
// Go ahead an save
$scope.pushInductee();
break;
case 'STATUS':
// just get the 'duplicate records check' sign off of there
// The save button is disabled by the critical error
$scope.hideSave = false;
break;
case 'ASSIGNED':
// just get the 'duplicate records check' sign off of there
// The save button is disabled by the critical error
$scope.hideSave = true;
break;
default:
$log.error(fault);
$location.path('/error/default');
}
} else {
$log.error(fault);
$location.path('/error/default');
}
};
$scope.getMatchingIndData()
.then($scope.procBusLogic)
.then($scope.pushInductee)
.catch(handleFault);
}
};
////HERE IS THE IMPORTANT PART I AM ASKING ABOUT
$scope.getMatchingIndData = function() {
var deferred = $q.defer();
var locals = {};
var checkUser = function(dupeJson){
var checkUserDeferred = $q.defer();
// abandoned promise replaced with my own
sttiJoinDataFactory.checkIfUserExistsNurseleader(dupeJson)
.then(function(results) {
var data = results.data;
if (angular.isArray(data) && data.length > 0){
var highestMatch = data[0];
for (var i = 0; i < data.length; i++) {
if (parseInt(data[i].Score) > parseInt(highestMatch.Score)) {
highestMatch = data[i];
}
}
checkUserDeferred.resolve(highestMatch);
} else {
// Reject the 'overall' promise here
// to effectively break the chain
return deferred.reject('NODATA');
}
})
.catch(function(fault) {
// Any other failure should break the chain
// of http requests at this point
return deferred.reject(fault);
});
return checkUserDeferred.promise;
},
loadindividual = function (highestMatch) {
return $http stuff about the highestmatch
// set data in locals
},
parallelLoadStatusAndInducteeData = function(individual) {
return another $http promise based on the last then()
// set data in locals
},
loadCeremonyData = function (inductees){
return another $http promise based on the last call then() // set data in locals
},
reportProblems = function( fault ) {
deferred.reject(fault);
};
checkUser($scope.generateDupJson())
.then(loadindividual, reportProblems)
.then(parallelLoadStatusAndInducteeData, reportProblems)
.then(loadCeremonyData, reportProblems)
.then(function() {
deferred.resolve(locals);
})
.catch( reportProblems );
return deferred.promise;
};
Must I take into account the abandoned promise, since I really need to promise to resolve when the data comes back, and i need to reject it if there is NODATA. This is handled in the calling function's chain.
Also, I'm aware of antipatterns here. I'm trying my best to not nest promises, maintain the chain, as well as handle exceptions.
Ok I have a few comments for you:
...
// revert if and return immediately
// to reduce indentation
if (typeof(fault) !== 'string') {
$log.error(fault);
$location.path('/error/default');
return;
}
switch (fault.toUpperCase()) {
...
You don't need deferred objects:
var checkUser = function(dupeJson){
// this is not abandoned because we are returning it
return sttiJoinDataFactory.checkIfUserExistsNurseleader(dupeJson)
.then(function(results) {
var data = results.data;
if (!angular.isArray(data) || data.length <= 0) {
return $q.reject('NODATA');
}
var highestMatch = data.reduce(function (highest, d) {
return parseInt(d.Score) > parseInt(highest.Score) ?
d : highest;
}, data[0]);
return highestMatch;
}); // you don't need catch here if you're gonna reject it again
}
...
checkUser(...)
// loadIndividual will be called
// after everything inside checkUser resolves
// so you will have your highestMatch
.then(loadIndividual)
.then(parallelLoadStatusAndInducteeData)
.then(loadCeremonyData)
// you don't need to repeat reportProblems, just catch in the end
// if anything rejects prior to this point
// reportProblems will be called
.catch(reportProblems)
...
There's a for loop and inside the for loop I'm calling an AJAX request. The issue I encountered is, the for loop finishes before the requests complete.
I want the for loop to continue to it's next iteration only after the required AJAX request completes.
PS- AJAX works fine. I do get my desired information from the server. It's just the for loop iterations complete first without waiting for the AJAX request success function to fire up. So when the AJAX success function finally fires the value in the variable cid is inconclusive as it has been overwritten by the last iteration of the for loop.
I want the for loop to continue only after the AJAX success function is executed.
Code:
if (window.cordova) {
db = $cordovaSQLite.openDB("my.db"); //device
} else {
db = window.openDatabase("my.db", '1', 'my', 1024 * 1024 * 100); // browser
}
var query = "SELECT * FROM order_product";
$cordovaSQLite.execute(db, query, []).then(function(res) {
if (res.rows.length > 0) {
for (var i = 0; i < res.rows.length; i++) {
console.log(" foreach SELECTED shopcart-> " + res.rows.item(i).id);
var cid = res.rows.item(i).coffee_id;
$http.post("http://192.168.1.4/coffeepayWeb/public/index.php/getsugar", {
cid: cID
})
.success(function(result) {
console.log("success");
if (cid == 6) {
//do something
} else {
//do something else
}
});
}
}
}
Using for is unsafe for asynchronous operations if you need the iteration index, use it only to store the required values to make the async operation ($http.post in this case), it should looks like:
var items = [];
for (var i = 0; i < res.rows.length; i++) {
var item = res.rows.item(i);
items.push(item);
}
after consider that $http returns a promise, then you should be able to map all elements from items
var getsugarUrl = 'http://192.168.1.4/coffeepayWeb/public/index.php/getsugar';
// Map the values to obtain the promises on each $http operation, the allSettled method of the
// [Kriskowal Q library](https://github.com/kriskowal/q/wiki/API-Reference) will be simulated
// this is because when one of the http requests fail then the $q.all method break and reject with an error
var promises = items.map(function (item) {
var cid = item.coffee_id;
return $http.post(getsugarUrl, { cid: cid })
.then(function (result) {
// You can take advantage of this closure to handle the result of the request an the
// cid property, store your modified result on the value property from the return
return {
state: 'fullfilled',
value: {
result: result,
cid: cid
} // your modified result
};
})
// Handle when the http request fails
.catch(function (err) {
return {
state: 'rejected',
error: err
};
});
});
finally handle the results obtained using $q.all (you need to inject the $q service)
$q.all(promises)
.then(function (responses) {
// iterate over the results
responses
.filter(function(response) { // only fullfilled results
return response.state == 'fullfilled';
})
.forEach(function (response) {
if (response.value.cid == 6) {
//do something with response.value.result
} else {
//do something else
}
});
});
With this solution the http requests aren't resolved sequentially, but you have control over when they've finished together and you will have the correct value of cid
Check more about JavaScript Promises
$http uses promises, which means you need to think of the problem within the promise paradigm.
Consider a recursive option where you pass in an array of your cID's, and each call sends a $http.post for the 1st cID in the array; if the call succeeded, we continue recursively with a smaller array, until there are no more left.
One promise is created & returned in the 1st call, which is notified on each successful query (allowing you to do your per-cID logic), and finally resolved when all queries are done (or rejected if any query fails).
// This function is called without deferred;
// deferred is used on recursive calls inside the function
function doPost(url, cidList, deferred) {
if (deferred === undefined) {
deferred = $q.defer();
}
var cid = cidList[0];
$http.post(url, {cid: cid})
.success(function(result) {
// query succeeded; notify the promise
deferred.notify({cid: cid, result: result});
if (cidList.length > 1) {
// there are more items to process; make a recursive
// call with cidList[1:end]
doPost(url, cidList.slice(1), deferred);
} else {
// we're done; resolve the promise
deferred.resolve();
}
})
.error(function(message) {
// there was an error; reject the promise
deferred.reject({cid: cid, message: message});
});
return deferred.promise;
}
// build the list of cIDs to pass into doPost
var cidList = [];
for (var i = 0; i < res.rows.length; i++) {
cidList.push(res.rows.item(i).coffee_id);
}
// start the queries
doPost("http://192.168.1.4/coffeepayWeb/public/index.php/getsugar", cidList)
.then(function() {
// promise resolved
console.log("All done!");
}, function(info) {
// promise rejected
console.log("Failed on cID " + info.cid + ": " + info.message);
}, function(info) {
// promise being notified
console.log("Just did cID " + info.cid + ": " + info.result);
// your per-cid handler
if (info.cid == 6) {
// do something
} else {
// do something else
}
});
UPDATE
Since the motivation for the question had more to do with variable scope (rather than sequential HTTP requests), this is all you really need:
// Build the CID list so that we can iterate it
var cidList = [];
for (var i = 0; i < res.rows.length; i++) {
cidList.push(res.rows.item(i).coffee_id);
}
// Iterate the list & call $http.post
cidList.forEach(function(cid) {
// your $http.post() logic; each call will have its own
// cid thanks to closures
});
Each iteration will have it's own cid, which you can use in your .success() or .error() handlers without worrying about it being overwritten. As with the other solution, the requests aren't sequential, but you probably didn't need them to be in the first place.