本文介绍了与MySQL一起使用的node.js异步/等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使所有结果同步,并使用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;
});

推荐答案

如果您恰好位于节点 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();
  }
})()

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

09-05 09:25
查看更多