Sunday, 4 June 2017

How to wait the end of multiple asynch methods for start a new process

I need to launch 3 methods asynchrone and I need to have an indication when the 3 methods are finished.

I use differents way to implemente this.

1) call back with an example server.js

class Server {
constructor() {
    var self = this:
    self.initServices_1( (response) => {
       if ( response ) {

       self.initServices_2( (response) => {
          if ( response ) {
            self.initServices_3( (response) => {
              if ( response ) {
              // ....
              }
            });
           }
       });
      }
    });        
}
initServices_1( (cb) => {
    /**  Code  with cb( true ) or promise  with resolve(true) **/
});
initServices_2( (cb) => {
    /** Code  with cb( true ) or promise  with resolve(true) **/
});
initServices_3( (cb) => {
    /** Code  with cb( true ) or promise  with resolve(true) **/
});
}

2) a different way to use generator

class server {
  constructor() {
    this.startFolder = null;
    //this.initServices();

    let asyncProcess = this.asyncService();
    let res = asyncProcess.next().value;

    res.then( (resp) => {

        console.log( "resp = ", resp );
        let res_1 = asyncProcess.next().value;

        res_1.then( (resp_1) =>  {

            console.log( "resp_1 = ", resp_1 );
            let res_2 = asyncProcess.next().value;

            res_2.then( (resp_2) =>  {
                console.log( "resp_2 = ", resp_2 );
            });

        });
    });
}

initServices_1( (cb) => {
    /**  Code  with cb( true ) or promise  with resolve(true) **/
});
initServices_2( (cb) => {
    /** Code  with cb( true ) or promise  with resolve(true) **/
});
initServices_3( (cb) => {
    /** Code  with cb( true ) or promise  with resolve(true) **/
});

* asyncService () {
    let arrResponse = [];
    arrResponse[0] = yield serviceRss.initServices_1();
    arrResponse[1] = yield serviceRss.initServices_2();
    arrResponse[2] = yield serviceRss.initServices_2();
    return arrResponse;
}

}

this methods work but i would like to not use the callback ? It's possible in javascript to wait the end of multiple asynchrone methods and start the new process after ? the order is not important, the method initServices_3 can finish before initServices_1.



via Seb

No comments:

Post a Comment