Node.js MySQL连接,查询顺序和事件循环 [英] Node.js MySQL connection, queries order and Event Loop

查看:125
本文介绍了Node.js MySQL连接,查询顺序和事件循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们看看这个例子

conn.query('SET @v = 1;', (err) => {
    conn.query('SELECT @v;', (err, res) => {
       // res contains @v = 1 or 2 ?
    });
});

conn.query('SET @v = 2;', (err) => {
    conn.query('SELECT @v;', (err, res) => {
        // res contains @v = 1 or 2 ?
    });
});

mysql/mysql2节点程序包是否保证MySQL查询的顺序?

Does mysql/mysql2 node packages guarantee MySQL queries order or not?

推荐答案

是的,mysql和mysql2都保留顺序.在下面的示例中,执行顺序由数字表示

Yes, both mysql and mysql2 preserve the order. In following example order of execution is indicated by number

conn.query('query 1', (err) => {
    conn.query('query 3', (err, res) => {
    });
});

conn.query('query 2', (err) => {
    conn.query('query 4', (err, res) => {
    });
});

首先,将查询1"和查询2"放置到命令队列中.然后,在查询1"完成之后,将查询3"添加到队列中(现在是查询2,查询3").完成查询2"后,将调用其回调函数,结果将查询4"添加到队列中.

First, "query 1" and "query 2" are placed to command queue. Then after "query 1" is complete "query 3" is added to queue ( now it's "query 2, query 3" ). After "query 2" is complete it's callback function is called and as a result "query 4" is added to queue.

这更多是协议属性,而不仅仅是驱动程序的功能. Mysql协议仅允许您在完全完成后在当前命令之后发送下一个命令,并且该协议是半双工"的.实际并行运行两个sql查询的唯一方法是打开2个单独的连接.

This is more of a protocol property, not just driver's feature. Mysql protocol only allows you to send next command only after current command if fully complete, and is in a way "half duplex". The only way to actually run two sql queries in parallel is to open 2 separate connections.

这篇关于Node.js MySQL连接,查询顺序和事件循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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