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.
update : i publish the solution I use co.js , it's very interesting lib (https://github.com/tj/co ).
co(function *(){
// resolve multiple promises in parallel
var a = initServices_1();
var b = initServices_2();
var c = initServices_3();
var res = yield [a, b, c];
console.log(res);
})
.then(res){
console.log(res);
}, function (err) {
console.error(err.stack);
});