node.js同步mysql查询 [英] node.js synchronous mysql query

查看:586
本文介绍了node.js同步mysql查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在node.js中同步使用mysql?我想执行查询并使用数据库中的数据来呈现正确呈现的表单,例如:

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}


推荐答案

按照标题,我认为您的意思是同步的。答案是你不能。这是因为NodeJS是单线程的,并且因为I / O(即与数据库的通信)是在单独的线程中处理的(NodeJS在内部使用它,所以它不适用于程序员),所以I / O的结果被推送到事件循环的顶部。但是NodeJS不能不离开当前事件就跳到事件循环中的另一个事件。

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.

这篇关于node.js同步mysql查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆