How to change the type of a Promise <> result in TypeScript

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.

+6
source share
1 answer

since returns Promise <void> becomes for me a common model

You can use a statement like

 initialiseApp( ): Promise< void > { let promises: Promise< any >[ ] = [ ]; promises.push( this.initLanguageStrings( ) ); promises.push( this.initModelData( ) ); promises.push( this.initUserInfo( ) ); return Promise.all( promises ) as Promise<void>; } 

Note: when you use a statement that you basically lay in the compiler in this case. Be careful with errors when the compiler thinks about one thing and the runtime sees another.

return Promise.all( promises ).then( ( ) => { } );

This is the right way to do this. The runtime corresponds to what was determined by the compiler. If you want a Promise<void> ... then create a Promise<void> , which is what this sample code does.

+4
source

All Articles