Skip to content

Instantly share code, notes, and snippets.

@dmitrythaler
Created November 20, 2016 21:51
Show Gist options
  • Save dmitrythaler/aec56248d2a45ef86d66015b02bcefe5 to your computer and use it in GitHub Desktop.
Save dmitrythaler/aec56248d2a45ef86d66015b02bcefe5 to your computer and use it in GitHub Desktop.
node.js waits until MySQL is up before init connection, promise based
const promise = require('bluebird');
const net = require('net');
const config = require('someConfigTool');
// ---------------------------------
// most probably MySQL server will start together with ours(this one)
// so we have to wait until it up
let tryOnce_ = (opts) => {
return new promise((resolve, reject) => {
let client = new net.Socket();
client.connect(opts, () => {});
client.on('data', function(data) {
client.destroy();
resolve(true);
});
client.on('error', function(err) {
client.destroy();
reject(err);
});
})
};
let try2Connect_ = ( opts, count ) => {
console.log( 'Connection attempt' );
return tryOnce_( opts )
.catch( function( err ) {
return promise.delay(1000/*assuming 1 sec, could be parameter*/)
.then( function() {
return --count ? try2Connect_( opts, count ) : promise.reject( err )
});
});
};
let DB_ = false;
let initDB_ = () => {
return DB_ ?
promise.resolve() :
try2Connect_({
host: config.db.host,
port: config.db.port // i.e. 3306
}, 30/*attempts number*/ )
.then( data => {
console.log( 'MySQL is up.' );
DB_ = new whateverToInitDB({ /**/ })
})
.catch( err => {
console.log('MySQL server does not response: ' + err.toString() );
throw err;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment