I have an i18n service in my application which contains the following code:
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 idea is that the user would call ensureLocaleIsLoaded
and wait for the promise to be resolved. But given that the purpose of the function is to only ensure that the locale is loaded, it would be perfectly fine for the user to invoke it several times.
I’m currently just storing a single promise and resolve it if the user calls the function again after the locale has been successfully retrieved from the server.
From what I can tell, this is working as intended, but I’m wondering if this is a proper approach.
Advertisement
Answer
As I understand promises at present, this should be 100% fine. The only thing to understand is that once resolved (or rejected), that is it for a defered object – it is done.
If you call then(...)
on its promise again, you immediately get the (first) resolved/rejected result.
Additional calls to resolve()
will not have any effect.
Below is an executable snippet that covers those use cases:
var p = new Promise((resolve, reject) => { resolve(1); reject(2); resolve(3); }); p.then(x => console.log('resolved to ' + x)) .catch(x => console.log('never called ' + x)); p.then(x => console.log('one more ' + x)); p.then(x => console.log('two more ' + x)); p.then(x => console.log('three more ' + x));