-1

How can I use mysql synchronously in node.js ? I want to execute query and render properly rendered form with datas from database, like:

userData = db.query "SELECT * FROM users WHERE id=1"
form.bind(userData)
res.render 'user/edit', {'form' : form}
mitch
  • 2,235
  • 3
  • 27
  • 46
  • 1
    [A bit of research will go a long way.](https://github.com/felixge/node-mysql) – robertklep Apr 09 '13 at 13:08
  • I have read a lot of articles but I can't find a solution. Maybe some example if you are so smart ? – mitch Apr 09 '13 at 13:16
  • Did you actually read the page I linked to? It contains example code. – robertklep Apr 09 '13 at 13:17
  • Yes, It's not an answer. This method uses callbacks. I don't want use callbacks. It will not work with this: result = connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) { if (err) throw err; return rows[0].solution; }); – mitch Apr 09 '13 at 13:20
  • Your question is "how can I use mysql in node.js", for which I provided a link (*not* an answer). But if you don't want to use callbacks, you're pretty much out of luck, it's Node we're talking about after all. – robertklep Apr 09 '13 at 13:28
  • Callbacks are definitely weird at first but worth learning if you want to work with node. There are some great resources out there for learning how to write async code. For example http://stackoverflow.com/questions/4506240/understanding-the-concept-of-javascript-callbacks-with-node-js-especially-in-lo – Noah Apr 09 '13 at 13:29
  • Read whole my question "I wan to get something like this...". I am sure there is a solution – mitch Apr 09 '13 at 13:30
  • @MichałK. Sorry to disappoint you, there's no solution to your problem except for changing technology to something else. – freakish Apr 09 '13 at 13:37
  • @MichałK how are we supposed to know what you mean by "**something** like this"? – robertklep Apr 09 '13 at 13:40
  • @robertklep: I have a little updated my question. It's simply, I want to get mysql query result in in variable and after that do other things, like in php. – mitch Apr 09 '13 at 13:43
  • @MichałK that's not how Node works. – robertklep Apr 09 '13 at 13:45
  • @MichałK. *like in php*. You are taking the wrong approach. It is **not** php, doing things like PHP complete defeats the purpose of using Node. – Tchoupi Apr 10 '13 at 01:24

1 Answers1

3

By the title I assume that you mean in a synchronous way. The answer is you can't. This is because NodeJS is single-threaded and since I/O (i.e. communication with database) is handled in a separate thread (which is used internally by NodeJS, it is not available for programmers) the result of I/O is pushed to the top of the event loop. But NodeJS can't jump to another event in the event loop without leaving current event.

Whether you like it or not you have to stick with asynchronous patterns.

freakish
  • 54,167
  • 9
  • 132
  • 169