Javascript node.js async/await 与 MySQL 一起使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44004418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
node.js async/await using with MySQL
提问by Burc Hasergin
I need to get all results synchronized and append to a string with async/await keywords like c#.
我需要同步所有结果并附加到带有 async/await 关键字(如 c#)的字符串。
I am new to node.js and I can not adapt this new syntax to my code.
我是 node.js 的新手,我无法将这种新语法应用于我的代码。
var string1 = '';
var string2 = '';
var string3 = '';
var string4 = '';
DatabasePool.getConnection(function(err, connection) {
connection.query(query,function (err, result) {
if (err){};
string1 = result;
});
connection.query(query,function (err, result) {
if (err){};
string2 = result;
});
connection.query(query,function (err, result) {
if (err){};
string3 = result;
});
connection.query(query,function (err, result) {
if (err){};
string4 = result;
});
//I need to append all these strings to appended_text but
//all variables remain blank because below code runs first.
var appended_text = string1 + string2 + string3 + string4;
});
回答by LeOn - Han Li
if you happen to be in Node 8+, you can leverage the native util.promisify()with the node mysql.
如果您碰巧在 Node 8+ 中,则可以利用util.promisify()节点 mysql来利用本机。
Do not forget to call it with bind()so the thiswill not mess up:
不要忘记调用它,bind()这样this就不会搞砸了:
const mysql = require('mysql'); // or use import if you use TS
const util = require('util');
const conn = mysql.createConnection({yourHOST/USER/PW/DB});
// node native promisify
const query = util.promisify(conn.query).bind(conn);
(async () => {
try {
const rows = await query('select count(*) as count from file_managed');
console.log(rows);
} finally {
conn.end();
}
})()
回答by mr_squall
Use mysql2 packet. It has promise wrapper so you can do that:
使用 mysql2 数据包。它具有承诺包装器,因此您可以这样做:
async function example1 () {
const mysql = require('mysql2/promise');
const conn = await mysql.createConnection({ database: test });
let [rows, fields] = await conn.execute('select ?+? as sum', [2, 2]);
}
回答by adam-beck
Assuming that your ORM that you are using it promise-based you can do something like this
假设您使用的是基于承诺的 ORM,您可以执行以下操作
async function buildString() {
try {
const connection = await DatabasePool.getConnection();
const string1 = await connection.query(query);
const string2 = await connection.query(query);
const string3 = await connection.query(query);
const string4 = await connection.query(query);
return string1 + string2 + string3 + string4;
} catch (err) {
// do something
}
}
Any promise can be used with async/await by putting awaitin front of the call. However, notice that thisfunction must be used within an asyncfunction "wrapper". You need to handle the errors in try/catchblocks.
任何承诺都可以通过放在await调用前面来与 async/await 一起使用。但是,请注意此函数必须在async函数“包装器”中使用。您需要处理try/catch块中的错误。
I also want to point out that these 4 queries are notrun simulatneously. You'll still need to use Promise.all for that.
我还想指出,这 4 个查询不是同时运行的。为此,您仍然需要使用 Promise.all。
回答by Alexis Wilke
If you want to use mysql (also called mysqljs) you have to do a little bit of work if you don't want to use a wrapper. But it's easy enough. Here is how the connect function would look like:
如果您想使用 mysql(也称为 mysqljs),如果您不想使用包装器,则必须做一些工作。但这很容易。下面是 connect 函数的样子:
const mysql = require('mysql')
var my_connection = mysql.createConnection({ ... })
async function connect()
{
try
{
await new Promise((resolve, reject) => {
my_connection.connect(err => {
return err ? reject(err) : resolve()
})
})
}
catch(err)
{
...handle errors...
}
}
connect()
As you can see the await will know how to handle a promise. You create such and use the resolve/reject functions in the callback implementation. That's all there is to it, really, so using a wrapper may be a bit much unless you access your database a lot.
如您所见,await 将知道如何处理承诺。您创建此类并在回调实现中使用解析/拒绝函数。这就是它的全部内容,真的,因此除非您经常访问数据库,否则使用包装器可能会有点多。
回答by Explosion Pills
You would have to make sure that the mysql library you are using either supports Promises, which are required by async/await, or use a tool like Bluebird's promisifyAllto wrap the library.
您必须确保您使用的 mysql 库支持async/所需的 Promises await,或者使用Bluebird 之promisifyAll类的工具来包装库。
async function appendedText() {
const connection = await DatabasePool.getConnectionAsync();
const [string1, string2, string3, string4] = await [
connection.query(query1),
connection.query(query2),
connection.query(query3),
connection.query(query4),
];
return string1 + string2 + string3 + string4;
}
Note that calling appendedText()will actually return a Promise and not a value.
请注意,调用appendedText()实际上会返回一个 Promise 而不是一个值。
appendedText().then(appended_text => {});
回答by Pathum Kalhan
It seems you use mysqljswhich isn't a promised based library. So you can't achieve what you want using this library. So what you can do is use a promised based library like Sequelizeor else as a comment suggests:
看来您使用的是mysqljs,它不是基于承诺的库。所以你不能使用这个库来实现你想要的。因此,您可以做的是使用像Sequelize这样承诺的基于库的库,或者如评论所示:
use a tool like Bluebird's promisifyAll to wrap the library.
使用 Bluebird 的 promisifyAll 之类的工具来包装库。
I don't know much about wrapping thing, so what I did was to switch to the sequelize.
我对包装东西不太了解,所以我所做的是切换到续集。

