How to associate 3 Promises with angular2 and typescript

I successfully chained promises, but I found a way that I did it quite difficult: I wonder if there is a more elegant way to do this.

I am using Angular2, Typescript and signalR.

I have a getIntervention service that returns an object from the server by identifier.

Before calling getIntervention I want to verify that the client is connected to the server, and before connecting to the server, I want SignalR scripts to load.

So, I created the first promise scriptLoadedPromise , which is waiting for the SignalR script to load. When scriptLoadedPromise enabled, a new connectionPromise promise is created that is waiting for the connection to be established.

When connectionPromise enabled, call the getIntervention service.

For each promise, I added callbacks called scriptLoaded and connectionDetected that call resolve() .

Here is my code:

 public loadIntervention( numFI : number ) : Promise<Intervention> { let scriptLoadedPromise : Promise<Intervention> = new Promise( ( resolve, reject ) => { // si le script est chargé alors la promesse est déjà tenue if ( this.isScriptLoaded ) resolve(); else this.scriptLoaded = ( () => { resolve(); } ) ; }).then ( () => { let connectionPromise : Promise<Intervention> = new Promise( (resolve, reject) => { // si le serveur est connecté alors la promesse de connection est déjà tenue if ( this.Connected ) resolve(); else this.connectionDetected = ( () => { console.log("RECONNETED !!!!!"); resolve(); } ); } ) .then( () => { return this.proxy.server.getIntervention( numFI ); } ); return connectionPromise; }); return scriptLoadedPromise; } 

Is there a way to simplify this implementation where 3 promises are chained?

+5
source share
1 answer

If these promises depend on each other, it looks like what you have already created. You can improve the style of the code by adding logic to individual methods, for example,

 private firstAction():Promise<any> { return new Promise<any>( (resolve, reject) => { ... } ); } private secondAction():Promise<any> { return new Promise<any>( (resolve, reject) => { ... } ); } execute() { this.firstAction().then( (firstResult:any) => this.secondAction().then( (secondResult:any) => { ... } ); ) } 

If running promises in parallel is allowed, you can use Promise.all() , for example,

 execute() { let promises:Promise<any>[] = []; promises.push(this.firstAction()); promises.push(this.secondAction()); Promise.all(promises).then( () => { ... } ); } 
+6
source

Source: https://habr.com/ru/post/1261778/


All Articles