简体   繁体   中英

How to chain 3 Promises with angular2 and typescript

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 ?

If these promises depend on each other, it's similar to what you created already. You could enhance the code-style of that, by putting the logic into separate methods like eg

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 it's allowed that the promises are executed in parallel, you can make use of Promise.all() , like eg

execute() {
  let promises:Promise<any>[] = [];
  promises.push(this.firstAction());
  promises.push(this.secondAction());

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM