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?
source share