for example i have two services: db and queue I need to start server after db and amqp connects to their servers.
for now i have something like this server.js:
let mongo = require('./server/db');
let qManager = require('./server/amqp');
mongo.connect(()=>{
qManager.connect(()=>{
http.listen(3001, function () {
console.log('listening on *:3001');
});
});
});
mongo connection method:
const connectDb = (callback) => {
if (state.db) return state.db;
let connection = MongoClient.connect(mongoUrl, (err, db) => {
if (err) {
connectDb();
}
state.db = db;
console.log('Mongo connected.');
callback();
});
};
rabbitmq connection method:
const connect = (callback) => {
connection = amqp.connect(url)
.then(conn => {
module.connection = conn;
channel = conn.createChannel();
console.log('Queue connected.');
pythonResultListener();
callback()
})
.catch(err => {
console.error('Connect failed: %s', err);
});
return connection;
};
maybe there is much better way? thanks.
There are several approaches to handle asynchronous flow. For your particular case:
promises approach
generators/coroutines
async/await
Very quick example with async/await
:
// First you modify your callback function to be promises
// For example mongoconnect method implementation:
const connectDb = function() {
return new Promise (resolve, reject) => {
if (state.db) return state.db;
let connection = MongoClient.connect(mongoUrl, (err, db) => {
if (err) return reject(err);
state.db = db;
console.log('Mongo connected.');
resolve();
});
});
};
And now, assuming you have promises A, B, C, your goal is to call them one by one:
const promises = [ A, B, C ];
for (const promiseFunc of promises) {
const res = await promiseFunc();
// For cases you need to return something
console.log(res);
}
More info you can find here.