node.js async/await 与 MySQL 一起使用
我需要同步所有结果并附加到带有 async/await 关键字(如 c#)的字符串.
I need to get all results synchronized and append to a string with async/await keywords like c#.
我是 node.js 的新手,我无法将这种新语法应用于我的代码.
I am new to node.js and I can not adapt this new syntax to my code.
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;
});
推荐答案
如果你碰巧在 Node 8+ 中,你可以利用原生的 util.promisify()
使用节点 mysql.
if you happen to be in Node 8+, you can leverage the native util.promisify()
with the node mysql.
不要忘记用 bind()
调用它,这样 this
就不会搞砸了:
Do not forget to call it with bind()
so the this
will not mess up:
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();
}
})()
相关文章