I have successfully chained promises, but I find the way I did it enough complicated: I'm wondering if there is not a more elegant way to do it.
I use Angular2, Typescript and signalR.
I have a service getIntervention
that returns an object from the server by Id.
Before calling getIntervention
, I want to check the client to be connected to the server, and before connecting to the server, I want the SignalR scripts to be loaded.
So I created a first promise scriptLoadedPromise
that waits for the SignalR script to be loaded. When scriptLoadedPromise
is resolved a new promise connectionPromise
is created that waits for the connection to be established.
When connectionPromise
is resolved, call the service getIntervention
.
For each promise I added callbacks named 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 that implementation where 3 promises are chained ?