简体   繁体   English

在Node.js中使用JS Promise进行多个mysql调用

[英]Making multiple mysql calls using JS promise in Node.js

GOAL: 目标:

I am trying to make multiple SQL queries using the "mysql" module in Node.js such that the result of one query is used as input in the next statement. 我正在尝试使用Node.js中的“ mysql”模块进行多个SQL查询,以便将一个查询的结果用作下一条语句的输入。

sql1 = SELECT id FROM users WHERE email=? // get user id from email
val1 = test@email.com

sql2 = SELECT something FROM profiles WHERE user_id=?
val2 = user_id // result of sql1

APPROACH: 方法:

I am using a JS "promise" to achieve this: 我正在使用JS“承诺”来实现这一目标:

var run_query = function(conn,sql){

return new Promise(function (fulfill, reject){

    conn.query(sql, val, function(err, res) {

        if(err) reject(err);
        else    fulfill(res);

    });

});

}

var conn = db.config(mysql);

run_query(conn,[ 'SELECT id FROM users WHERE email=?' , ['test@email.com'] ]).then(function(result){

  console.log(result.id); // result of 1st query

  return run_query(conn,[ 'SELECT something FROM profiles WHERE user_id=?' , [result.id] ]);

}).then(function(result){

    console.log(result.something); // result of 2nd query 

}).catch(function(err){

    console.log('there was an error', err);

});

conn.end();

ISSUE: 问题:

The 1st query returns the correct result, but the second query throws the following error from the mysql module: 第一个查询返回正确的结果,但是第二个查询从mysql模块抛出以下错误:

Error: Cannot enqueue Query after invoking quit.
~blah blah blah~
code: 'PROTOCOL_ENQUEUE_AFTER_QUIT', fatal: false 

MY ATTEMPTS TO RESOLVE: 我要解决的尝试:

I believe this has something to do with multiple calls being made while the connection is open and conn.end(); 我相信这与打开连接和conn.end();时进行多次调用有关 being called at the very end. 在最后被调用。 I moved it around a bit but that didnt work. 我移动了一下,但是没有用。

I tried turning on multiple statement for the mysql module 我尝试为mysql模块打开多条语句

var conn = mysql.createConnection({multipleStatements: true}); 

..but that didnt work either. ..但是那也不起作用。

How does one use the mysql node module with a JS promise structure? 如何使用带有JS promise结构的mysql节点模块?

You are using promise but the promise code is synchronse and outer code is asynchronse . 您正在使用promise,但是promise代码是同步的,而外部代码是asynchronse。 so conn.end run before your second query. 因此conn.end在第二个查询之前运行。

Use conn.end inside second .then block like this and remove outer conn.end : 在第二个conn.end内使用conn.end ,然后像这样阻止并删除外部conn.end

var conn = db.config(mysql);

run_query(conn,[ 'SELECT id FROM users WHERE email=?' ,
['test@email.com'] ]).then(function(result){

 console.log(result.id); // result of 1st query

 return run_query(conn,[ 'SELECT something FROM profiles WHERE
user_id=?' , [result.id] ]);

}).then(function(result){

   console.log(result.something); // result of 2nd query 
    conn.end();
}).catch(function(err){

   console.log('there was an error', err);

});

Promises explicitly is used to write cleaner code but you are doing quite the opposite. 显式地使用Promises来编写更简洁的代码,但与此相反。

What Himanshu said is right your conn.end() is executed first. Himanshu所说的对,您的conn.end()首先执行。 Given your use case I'd suggest you to use Async Module Click Here . 鉴于您的使用情况下,我建议你使用Async模块点击这里 Go through features available once. 浏览一次可用的功能。

I think Async.series will server you right although there are multiple async features that can help your case, notably, queue. 我认为Async.series将为您服务,尽管有多种异步功能可以帮助您解决问题,尤其是排队。

async.series([
    function(callback) {
     //Your First SQL Query based on response send success or failure callback
        callback(null, 'one');
    },
    function(callback) {
     //Your Second SQL Query based on response send success or failure callback
        callback(null, 'two');
    }
],
// optional callback
function(err, results) {
    //listen to results from your codes and put some logic based on what you want and close the connection here
conn.close();
});

Doubt : Why do you want to execute them one by one? 疑问:为什么要一一执行?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM