To ensure that the data from an asynchronous operation is retrieved correctly, it is recommended to return the promise from the source and use it in the OpenModal
function. This approach guarantees that whenever the modal is clicked, the data will always be returned without any synchronization issues.
$scope.loadEvents = function () {
var items = listEvents();
return items.then(function (data) { //Ensure loadEvents returns a promise
return data; //Return the data after any necessary processing
});
};
$scope.openModal = function (data) {
$scope.loadEvents().then(function(data){ //
lastTime = data;
});
};
To prevent multiple simultaneous calls before receiving a response from the server, you can reuse the same promise created earlier.
var _cachedPromise;
$scope.loadEvents = function () {
var items = listEvents();
if(_cachedPromise) return _cachedPromise;
_cachedPromise = items.then(function (data) { //Ensure loadEvents returns a promise
return data; //Return the data after any necessary processing
});
_cachedPromise.finally(function(){
_cachedPromise = null;
});
return _cachedPromise;
};
It is advisable to handle this promise caching logic in the service rather than the controller...