AngularJS non-async posting - angularjs

I have two $http posts that each post arrays of objects in a loop. The problem is that the second $http post is reliant on the first one completing. Is there a way to make them not async calls? I tried to used deferred but something is wrong in it as it is not working. It still fires group saving while tag saving is going on.
Angular:
var deferred = $q.defer();
var all = $q.all(deferred.promise);
for (var property in data.tagAdded) {
if (data.tagAdded.hasOwnProperty(property)) {
$http({
method: "POST",
url: '/api/projects/' + data.Project.Id + '/tags',
data: ({ Name: data.tagAdded[property].tag.Name })
}).success(function (response) {
deferred.resolve(response);
data.tagAdded[property].tag.Id = response.Data[0].Id;
data.tagAdded[property].tag.ProjectId = response.Data[0].ProjectId;
}).error(function (response) {
tagError = true;
$.jGrowl("Error saving new tags. Contact support.", { header: 'Error' });
});
}
}
deferred.promise.then(function() {
console.log(data);
});
all.then(function() {
groups.forEach(function(group) {
$http({
headers: { 'Content-Type': 'application/json; charset=utf-8' },
method: "POST",
url: '/api/projects/' + data.Project.Id + '/recruiting-groups',
data: angular.toJson(group, false)
}).success(function(response) {
}).error(function(response) {
recError = true;
$.jGrowl("Error saving recruiting group. Contact support.", { header: 'Error' });
});
});
});

Going without promises is totally not what you want to do here. In fact, this is exactly the kind of situation where promises shine the most! Basically, you weren't using $q.all properly. You can just pass it a list of promises, and it will be resolved when they are all resolved. If any one of them fails, it will yield a rejected promise with the same rejection as the first one that failed. You can of course swallow that rejection via a .catch invocation that returns anything other than a $q.reject value.
I reimplemented what you had using promises. Both .success and .error are fairly limited, so I used the traditional .then and .catch methods here.
/**
* Here we define a function that takes a property, makes a POST request to
* create a tag for it, and then appends the promise for the request to a list
* called tagRequests.
*/
var tagRequests = [];
var createTag = function(property) {
tagRequests.push($http({
method: "POST",
url: '/api/projects/' + data.Project.Id + '/tags',
data: ({ Name: data.tagAdded[property].tag.Name })
}).then(function(response) {
var responseData = response.data;
data.tagAdded[property].tag.Id = responseData.Data[0].Id;
data.tagAdded[property].tag.ProjectId = responseData.Data[0].ProjectId;
return responseData;
}).catch(function (err) {
var errorMsg = "Error saving new tags. Contact support.";
$.jGrowl(errorMsg, { header: 'Error' });
// If we don't want the collective promise to fail on the error of any given
// tag creation request, the next line should be removed.
return $q.reject(errorMsg);
}));
};
/**
* We then iterate over each key in the data.tagAdded object and invoke the
* createTag function.
*/
for (var property in data.tagAdded) {
if (Object.prototype.hasOwnProperty.call(data.tagAdded, property)) {
createTag(property);
}
}
/**
* Once all tag requests succeed, we then map over the list of groups and
* transform them into promises of the request being made. This ultimately
* returns a promise that is resolved when all group POST requests succeed.
*/
$q.all(tagRequests)
.then(function(tagsCreated) {
return $q.all(groups.map(function(group) {
return $http({
headers: { 'Content-Type': 'application/json; charset=utf-8' },
method: "POST",
url: '/api/projects/' + data.Project.Id + '/recruiting-groups',
data: angular.toJson(group, false)
}).then(function(response) {
return response.data;
})
.catch(function(err) {
var errorMsg = "Error saving recruiting group. Contact support.";
$.jGrowl(errorMsg, { header: 'Error' });
// If we want this collective promise to not fail when any one promise is
// rejected, the next line should be removed.
return $q.reject(errorMsg);
});
}));
});
I highly suggest brushing up on Promises in general, and then taking another look at the $q documentation. I've also written this blog post on the way promises work in Angular and how they differ from most promise implementations.

This is exactly what promises do. Angular uses Kris Kowal's Q Library for promises. Check out the Angular docs page, has a perfect example of the promise pattern. Basically you would do the first call, then once it's promise returns success, make the second call.

I had to alter my code a bit, and get some coworker team work. I went completely without promises.
I use a counter to track when counter = 0 by adding to the counter then upon success/fail i decrement from the counter taking it backwards for each completed transaction. When counter is at 0 I am done then call my next bit $http post.
Angular Deferred:
var counter = 0;
var tags = [];
for (var property in data.tagAdded) {
if (data.tagAdded.hasOwnProperty(property)) {
tags.push({ Name: property });
}
}
if (tags.length == 0) {
groupInsert();
} else {
tags.forEach(function (tag) {
counter ++;
$http({
method: "POST",
url: '/api/projects/' + data.Project.Id + '/tags',
data: ({ Name: tag.Name })
}).success(function (response) {
console.log(response)
counter--;
data.tagAdded[property].tag.Id = response.Data[0].Id;
data.tagAdded[property].tag.ProjectId = response.Data[0].ProjectId;
if (counter == 0) {
groupInsert();
}
}).error(function (response) {
counter--;
tagError = true;
$.jGrowl("Error saving new tags. Contact support.", { header: 'Error' });
if (counter == 0) {
groupInsert();
}
});
});
}
function groupInsert() {
groups.forEach(function (group) {
console.log(group)
$http({
headers: { 'Content-Type': 'application/json; charset=utf-8' },
method: "POST",
url: '/api/projects/' + data.Project.Id + '/recruiting-groups',
data: angular.toJson(group, false)
}).success(function (response) {
}).error(function (response) {
recError = true;
$.jGrowl("Error saving recruiting group. Contact support.", { header: 'Error' });
});
});
}

Related

Node.js + Angular.js promises sync issue

I am working on a chat app which is Node.js + MongoDB (Mongoose library) on the server side, and Angular.js on the client side.
I have a database collection (MongoDB) for rooms (all the rooms in the app), which looks like this:
// ------- creating active_rooms model -------
var active_rooms_schema = mongoose.Schema({
room_name: String,
users: [String]
});
var active_rooms = mongoose.model('active_rooms', active_rooms_schema);
This database contains a room with all its users (i.e. "my cool room" with users: "mike", "joe", and "dave").
What I want to do is - every time a user wants to be in a chat room (with some room name) in my Angular.js client, I want to:
Create the room if it is not exists
Push that user into the users array of the room.
I know that because of 1, I will always have a room with an array of users.
This is my Angular relevant code: (I cannot give here the whole app because it is way too large and not relevant.)
$scope.enterRoom = function(info) {
$q.when(create_room_if_not_exists($scope.room)).then(add_user_to_room($scope.name, $scope.room));
$location.path("chat");
}
var create_room_if_not_exists = function(room_name) {
var deferred = $q.defer();
is_room_already_exists({
'name': room_name
}).then(function(response) {
if (!response.data.is_room_exists) {
register_room({
'name': room_name
});
console.log("room: " + room_name + ", was created");
deferred.resolve();
}
}, function(error) {
deferred.reject(error.data);
});
return deferred.promise;
}
var add_user_to_room = function(user_name, room_name) {
console.log(user_name)
add_user_to_room_request({
'user_name': user_name,
'room_name': room_name
});
}
var is_room_already_exists = function(info) {
return $http({
url: '/is_room_already_exists',
method: 'POST',
data: info
});
}
var add_user_to_room_request = function(info) {
$http({
url: '/add_user_to_room',
method: 'POST',
data: info
});
}
var register_room = function(info) {
return $http({
url: '/register_room',
method: 'POST',
data: info
});
}
What happens is that the 2nd action happens before the 1st one. When I print a log into the console, I see that, and I don't know why.
Both of these actions arrive through an HTTP request to the server - so I don't think the problem is there.
I am talking about the XHRs not chaining
A common cause of problems with chaining is failure to return promises to the chain:
var add_user_to_room = function(user_name, room_name) {
console.log(user_name)
//add_user_to_room_request({
return add_user_to_room_request({
//^^^^^^ ----- be sure to return returned promise
'user_name': user_name,
'room_name': room_name
});
}
If chaining is done properly, $q.defer is not necessary:
var create_room_if_not_exists = function(room_name) {
//var deferred = $q.defer();
//is_room_already_exists({
return is_room_already_exists({
//^^^^^^ --- be sure to return derived promise
'name': room_name
}).then(function(response) {
if (!response.data.is_room_exists) {
console.log("room: " + room_name + ", to be created");
//register_room({
return register_room({
//^^^^^^ ----- return promise to further chain
'name': room_name
});
//deferred.resolve();
} else {
return room_name;
//^^^^^^ ----- return to chain data
};
}, function(error) {
//deferred.reject(error.data);
throw error;
//^^^^^ ------- throw to chain rejection
});
//return deferred.promise;
}
If a promise is returned properly, $q.when is not necessary:
$scope.enterRoom = function(info) {
//$q.when(create_room_if_not_exists($scope.room))
// .then(add_user_to_room($scope.name, $scope.room));
return create_room_if_not_exists($scope.room)
.then(function() {
return add_user_to_room($scope.name, $scope.room));
}).then(function()
$location.path("chat")
});
}
The rule of thumb with functional programming is -- always return something.
Because calling the .then method of a promise returns a new derived promise, it is easily possible to create a chain of promises. It is possible to create chains of any length and since a promise can be resolved with another promise (which will defer its resolution further), it is possible to pause/defer resolution of the promises at any point in the chain. This makes it possible to implement powerful APIs.
-- AngularJS $q Service API Reference - Chaining Promises.
Try this:
$scope.enterRoom = function (info) {
return create_room_if_not_exists($scope.room)).then(function(){
return add_user_to_room_request({ 'user_name': $scope.name, 'room_name': $scope.name });
}).then(function(){
$location.path('chat');
});
}
var create_room_if_not_exists = function (room_name) {
var deferred = $q.defer();
return is_room_already_exists({ 'name': room_name }).then(function (response) {
if (!response.data.is_room_exists) {
console.log("room: " + room_name + ", is being created");
return register_room({ 'name': room_name });
}
return response;
})
}
var is_room_already_exists = function (info) {
return $http({
url: '/is_room_already_exists',
method: 'POST',
data: info
});
}
var add_user_to_room_request = function (info) {
return $http({
url: '/add_user_to_room',
method: 'POST',
data: info
});
}
var register_room = function (info) {
return $http({
url: '/register_room',
method: 'POST',
data: info
});
}

AngularJS success function of promise

I have made a HTTP post API call to a URL.
I am getting the response, but I am confused how to write a success function, as there are many ways for it.
Here's my API call. Please help me how would the success function would be like?
var req = {
method: 'POST',
url: viewProfileurl,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + $rootScope.token,
},
params: {
'action':'view'
}
}
$http(req);
Angular uses promise internally in $http implementation i.e. $q:
A service that helps you run functions asynchronously, and use their
return values (or exceptions) when they are done processing.
So, there are two options:
1st option
You can use the .success and .error callbacks:
var req = {
method: 'POST',
url: viewProfileurl,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + $rootScope.token,
},
params: {
'action': 'view'
}
}
$http(req).success(function() {
// do on response success
}).error(function() {
});
But this .success & .error are deprecated.
Official deprecation notice
http://www.codelord.net/2015/05/25/dont-use-$https-success/
So, go for the 2nd option.
2nd Option
Use .then function instead
var req = {
method: 'POST',
url: viewProfileurl,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + $rootScope.token,
},
params: {
'action': 'view'
}
}
$http(req).then(function() {
// do on response success
}, function() {
// do on response failure
});
You need to write a success callback to retrive the data returned by your API.
$http(req)
.then(function (response) {
var data = resposne.data;
...
}, function (error) {
var errorStatusCode = error.StatusCode;
var errorStatus = error.Status;
...
});
Basically $http returns a promise and you need to write a callback function.
Or you can do something like this:
$http(req).success(function(respData) { var data = respData; ... });
$http(req).error(function(err) { ... });
This is success and error syntax
$http.get("/api/my/name")
.success(function(name) {
console.log("Your name is: " + name);
})
.error(function(response, status) {
console.log("The request failed with response " + response + " and status code " + status);
};
Using then
$http.get("/api/my/name")
.then(function(response) {
console.log("Your name is: " + response.data);
}, function(result) {
console.log("The request failed: " + result);
};
$http returns a promise that has a then function that you can use.
$http(req).then(function (data) { ...; });
The definition of then:
then(successCallback, failCallback)

Access successCallback in AngularJs $http Method

I want to access to response successCallback(response)
var list_of_user = $http({
method: 'GET',
url: '/users/'
}).then(function successCallback(response) {
$scope.all_users = response.data;
}, function errorCallback(response) {
console.log(response);
});
console.log("$scope.all_users ", $scope.all_users)
is undefiend
I can access $scope.all_users from html, but how can I access to $scope.all_users in controller?
$http is async and console.log is executed before actually request is completed.
As you defined in comment that you want to compare two responses you can do that by simply putting a flag that will wait for both requests to finish.
var done = 0;
var onRequestFinishes = function() {
done += 1;
if (done < 2) {
return; // one of both request is not completed yet
}
// compare $scope.response1 with $scope.response2 here
}
and send first request and save response to $scope.response1 and invoke onRequestFinishes after that.
$http({
method: 'GET',
url: '/users/'
}).then(function successCallback(response) {
$scope.response1 = response.data;
onRequestFinishes();
}, function errorCallback(response) {
console.log(response);
});
Similarly send second request
$http({
method: 'GET',
url: '/users/'
}).then(function successCallback(response) {
$scope.response2 = response.data;
onRequestFinishes();
}, function errorCallback(response) {
console.log(response);
});
For request handling you can create individual promise chains and use $q.all() to execute code when all promises are resolved.
var request1 = $http.get('/users/').then(function(response)
{
console.log('Users: ', response.data);
return response.data;
}
var request2 = $http.get('/others/').then(function(response)
{
console.log('Others: ', response.data);
return response.data;
}
$q.all([request1, request2]).then(function(users, others)
{
console.log('Both promises are resolved.');
//Handle data as needed
console.log(users);
console.log(others);
}

Extract returning data from an angular promise

Greetings to everyone.
I'm trying to get data returned from an $http on angular. I created a factory:
.factory('MyFactory', function($http, SKURL) {
return {
all: function(my_data) {
return $http({
method: 'POST',
url: SKURL.url,
data: "data=" + my_data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
}
}
})
Then, in the controller, I write:
var n = MyFactory.all(my_data);
When I see console.log(n), I see the returned object is a promise: Promise {$$state: Object}. I see the data when I expand the object. But, when I try get n.$$state.value.data I get undefined. How can I get the data returned for the $http ?
In you controller, try the following instead:
var n;
MyFactory.all(my_data).then(function(response) {
n = response.data;
console.log(n); // this should print your data;
// do something with 'n' here.
}, function(err) {
// handle possible errors that occur when making the request.
});

AngularJS : factory function undefined in controller

I used to make it work the exact same way before, and it's driving me crazy. I want to perform a $http GET call into a factory and then get back the result into the controller, to be processed.
The factory (don't pay attention to the madness of the request url ):
App.factory('MessageFactory', function ($http) {
var MessageFactory = {
getCast: function () {
var request = {
method: "GET",
url: spHostUrl + "/_api/web/Lists/getByTitle('" + listTitle + "')/items?$select=AuthorId,Author/Name,Author/Title,Type_x0020_message,Title,Modified,Body,Expires,Attachments&$expand=Author/Id",
headers: {
"Content-Type": "application/json;odata=verbose",
"Accept": "application/json;odata=verbose"
}
};
$http(request)
.then(function (res) {
return res.data;
}).catch(function (res) {
console.error("error ", res.status, res.data);
}).finally(function () {
console.log("end");
});
}
};
return MessageFactory;
});
Now the controller :
App.controller('MessageController', function ($scope, $http, $log, $attrs, MessageFactory) {
$scope.messages = MessageFactory;
MessageFactory.getCast().then(function (asyncCastData) {
$scope.messages.cast = asyncCastData;
});
$scope.$watch('messages.cast', function (cast) {
//do stuff
});
});
When I test it I get the following error :
Error: MessageFactory.getCast(...) is undefined
#/Scripts/App.js:167:9
The line 167 is indeed this line in the controller
MessageFactory.getCast().then(function (asyncCastData) {
My app works fine for any other feature, so my issue appeared when adding this part, and I'm pretty sure my controller doesn't know my factory yet and thus try to access to his function. As it's an asynchronous call, it should work with the code in the controller. I need your help on this, thanks.
You must be getting .then of undefined error
Because you missed to return promise from service method.
Service
var MessageFactory = {
getCast: function() {
var request = {
method: "GET",
url: spHostUrl + "/_api/web/Lists/getByTitle('" + listTitle + "')/items?$select=AuthorId,Author/Name,Author/Title,Type_x0020_message,Title,Modified,Body,Expires,Attachments&$expand=Author/Id",
headers: {
"Content-Type": "application/json;odata=verbose",
"Accept": "application/json;odata=verbose"
}
};
return $http(request) //returned promise from here
.then(function(res) {
return res.data;
}).catch(function(res) {
console.error("error ", res.status, res.data);
}).finally(function() {
console.log("end");
});
}
};

Resources