Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 609
Anthony Brenelière Avatar asked Dec 23 '16 11:12

Anthony Brenelière


People also ask

Can promises be chained?

Example 2: Chaining the Promise with then() Promise resolved You can call multiple functions this way. In the above program, the then() method is used to chain the functions to the promise. The then() method is called when the promise is resolved successfully. You can chain multiple then() methods with the promise.

How do you handle nested promises?

In a promise nesting when you return a promise inside a then method, and if the returned promise is already resolved/rejected, it will immediately call the subsequent then/catch method, if not it will wait. If promised is not return, it will execute parallelly.

Can we use promises in Angular?

Promises in Angular provide an easy way to execute asynchronous functions that use callbacks, while emitting and completing (resolving or rejecting) one value at a time. When using an Angular Promise, you are enabled to emit a single event from the API.


1 Answers

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 e.g.

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 e.g.

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

  Promise.all(promises).then(
    () => { ... }
  );
}
like image 178
Oliver Hader Avatar answered Oct 21 '22 10:10

Oliver Hader