Kandrat
Kandrat

Reputation: 474

nodejs mysql without callbacks

Is there any way to execute mysql query synchronous? something like

getUser:function(user_id){
  return mysql_connection.query("select ... ");
},

to use it like this

var user = getUser(id);

Upvotes: 5

Views: 2700

Answers (1)

mscdex
mscdex

Reputation: 106736

In general the answer is no, unless you use a binding to libmysqlclient (or similar) that exposes such synchronous interfaces.

You want to avoid such synchronous interfaces because they will essentially keep you from doing anything else while the synchronous function is executing. For example, if you have a server running, that means you cannot service other clients. They all have to at least wait for your synchronous function to complete.

There are a plethora of ways to handle asynchronous tasks though, including "manual" callbacks (obviously), callback-based helper libraries like async, Promises, generators, async/await, etc. Some of these even create the illusion of a synchronous API without actually being synchronous.

Upvotes: 4

Related Questions