node mysql await,与MySQL一起使用的node.js async / await

I need to get all results synchronized and append to a string with async/await keywords like c#.

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;

});

解决方案

if you happen to be in Node 8+, you can leverage the native util.promisify() with the node mysql.

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();

}

})()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值