In my application, there is an i18n service that includes the following code snippet:
var i18nService = function() {
this.ensureLocaleIsLoaded = function() {
if( !this.existingPromise ) {
this.existingPromise = $q.defer();
var deferred = this.existingPromise;
var userLanguage = $( "body" ).data( "language" );
this.userLanguage = userLanguage;
console.log( "Loading locale '" + userLanguage + "' from server..." );
$http( { method:"get", url:"/i18n/" + userLanguage, cache:true } ).success( function( translations ) {
$rootScope.i18n = translations;
deferred.resolve( $rootScope.i18n );
} );
}
if( $rootScope.i18n ) {
this.existingPromise.resolve( $rootScope.i18n );
}
return this.existingPromise.promise;
};
The purpose of the ensureLocaleIsLoaded
function is to ensure that the locale is loaded. Therefore, it is designed so that users can call it multiple times without any issue.
Currently, I am storing a single promise and resolving it when the function is called again after successfully retrieving the locale from the server.
It seems like this approach is functioning correctly, but I'm curious if there might be a better way to handle this.