Currently, I am working on a single page application using angularJS and encountering some difficulties in storing asynchronous data.
In simple terms, I have a service that contains my data models which are returned as promises (as they can be updated asynchronously at any time).
There is an angular watch that updates these models based on certain conditions changes. Additionally, there is another angular watch that utilizes this data when certain conditions change.
The problem arises from the fact that the watch utilizing the data fires before the watch updating it, causing it to use the "stale" data instead of the new promise.
Here's an example of the code:
angular.module('myApp', [])
.controller('myController', function($scope, $q, asyncDataService) {
// Code snippet goes here
});
To overcome this issue, I currently resort to using setTimeout 0 before calling the promise, although I find this approach to be a bit cumbersome and not ideal in solving the root cause.
While I could request the data whenever needed, it would result in a significant number of unnecessary requests.
Simply watching the resolved promise isn't a viable solution either since other variables might trigger the watch as well, leading to incorrect firing only when that specific data is updated.