Jahongir Rahmonov Jahongir Rahmonov - 2 years ago 66
AngularJS Question

Controller method using old response from service promise after first time in AngularJS

I have this function inside my controller:

function getNewNotifications() {
.then(function (response) {
console.log("in controller: ", response.results);
vm.notificationCount = response.count;
},function (err) {

here is the
method of

function getNotifications(status) {
var thisUrl = url + '?status=' + status;

.success(function (data) {
console.log("in service: ", data.results);
.error(function (data) {

return deferer.promise;

Both of them log results in their success methods.

I call the controller function like this:

setInterval(getNewNotifications, 5000);

i.e. it gets new notifications every five seconds!

The first time the controller method is called, the browser logs are:

in service: Object
in controller: Object

As expected! However, after this, the order is reversed:

in controller: Object
in service: Object

This is weird and leading to other problems.

Why is this happening and how can I prevent it?

Answer Source

If the promise is created outside the getNotifications function it will already be resolved the second time the function is called, and the data from the first call will be returned again.

You simply need to recreate a new promise each time getNotifications is called.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download