node.js async/await 与 MySQL 一起使用 [英] node.js async/await using with MySQL

查看:53
本文介绍了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();
  }
})()

这篇关于node.js async/await 与 MySQL 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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