For some Typescript methods that I build, I often need the promise asynchrony, but I don't require the promise to return a value (conceptually speaking). A simple example would be to call the initLanguageStrings () method to load the language strings used by the application. Language strings fit in a global framework, but a promise is still needed to ensure that the application does not continue until language strings are loaded.
This script several times two or three times, and then I associate all the initialization work with a set of promises, which together must be completed before continuing. Therefore, I use Promise.all, for example (example):
initialiseApp( ): Promise< void > { let promises: Promise< any >[ ] = [ ]; promises.push( this.initLanguageStrings( ) ); promises.push( this.initModelData( ) ); promises.push( this.initUserInfo( ) ); return Promise.all( promises ); }
The code above does not actually compile (TS1.5 / 1.6), since Promise.all () returns Promise <any []> not Promise <void>.
So in the end I write the following:
return new Promise( ( resolve, reject ) => { Promise.all( promises ) .then( ( dummy: any[ ] ) => { resolve( ); } ); } );
I believe this is a semantically correct approach, because the "implementation" actually remains hidden, and the "internal promise" (from Promise.all) never "escapes" the calling element of initialiseApp ().
But on the other hand, I find this approach ugly and would like to find a more convenient way to do this, since Promise <void> returns are becoming quite common for me.
Is there a better way to achieve what I'm trying to do?
The compiler will allow:
return Promise.all( promises ).then( ( ) => { } );
But it also amazes me as "complex" and ugly.