Currently, this is how I perform a query using node-mysql
client.query( sql, function( error, result ) {
console.dir( result );
});
I would like to do this synchronously, something like this
var result = client.querySync( sql );
console.dir( result );
I understand why blocking in node is bad, but I’m (almost) grown up enough to know when it’s okay and when it’s not. I only intend to make synchronous calls at the initialisation stage, outside of any event loops.
Does anybody know how I can achieve this please?
Edit…
Something along the lines of…
client.querySync = function( sql )
{
var called = false;
var result;
while ( typeof result == 'undefined' ) {
if ( ! called ) {
called = true;
this.query( sql, function( error, _result ) {
result = { error: error, result: _result };
});
};
}
return result;
};
Your proposed solution (in your edit) won’t work because you never give up the thread (so the callback can never be called, so the variable can never be set, so your loop never breaks). Node is not multi-threaded – there is only ever one thread executing javascript at any one time. There is no way to yield that thread except by returning from whatever code is running.
So, you can’t do what you want to do. You could try to use some of the solutions that re-write your sync code into async behind the scenes, but I’ve personally found that approach isn’t really worth the effort — that’s it better to just bite the bullet and just do everything with callbacks (over time the pain subsides :).