Node.js mysql 结果到数组

Posted

技术标签:

【中文标题】Node.js mysql 结果到数组【英文标题】:Node.js mysql results to array 【发布时间】:2019-02-15 08:14:48 【问题描述】:

我一直在慢慢学习 node.js,以便我可以更好地整合我们当前的许多操作 (mysql) 和 Xero 会计。

我在 mysql 中有几个表,每个表用于 ["invoices","accounts","items","organisations","re​​ceipts","taxRates","users","trackingCategories"] 并且这些表中的每一个都有一个与其所在表同名的 JSON 列。这不是一个 json 问题。

发送类似 ""select "+ wewant1[i] + " from "+wewant1[i]" 的查询基本上是简单的“从发票中选择发票”并且易于迭代。

我可以将 mysql 结果列出,但需要将每个单独的“列表”作为结果数组获取。

我最终希望能够将“从发票中选择发票”的结果作为节点中的“发票”数组引用(发票 [0]、发票 [1] 等)。

我已尝试避免“回调地狱”,但仍然无法使其正常工作... 非常欢迎任何提示!

这是当前代码:

var mysql = require('mysql');

var con = mysql.createConnection(
  host: "10.0.1.103",
  user: "badayaba",
  password: "yadabuba",
  database: "xeroetc"
);

(async function() 

  let wewant1 = ["invoices", "accounts", "items", "organisations", "receipts", "taxRates", "users", "trackingCategories"];

  function getmydata(sql, result, callback) 
    var query = con.query(sql);
    query.on('result', function(row) 
      callback(null, row);
    );
  ;

  for (let i = 0; i < wewant1.length; i++) 
    var sql = "select " + wewant1[i] + " from " + wewant1[i];
    getmydata(sql, wewant1[i], function querydata(err, result) 
      console.log(err || result);
      return result;
    );
  ;
  con.end();
)();

20180910 22:00 GMT-6 谢谢史蒂文! 我想我明白了:

const XeroClient = require('xero-node').AccountingAPIClient;
const XeroErrors = require('xero-node').XeroError;
var mysql = require('mysql');

const config = 
    appType: "private",
    consumerKey: "_____",
    consumerSecret: "_____",
    privateKeyPath: "../../../ssl/_____.pem"
  ;

var con = mysql.createConnection(
    host: "_____",
    user: "_____",
    password: "_____",
    database: "xeroetc"
);


(async function()

let wewant1 = ["invoices","accounts","items","organisations","receipts","taxRates","users","trackingCategories"];

let xero = new XeroClient(config);

function getmydata(it, callback) 
       var sql = "select "+it+" from "+it;
       con.query(sql, function (err, result, fields) 
        if (err) throw err;
        callback(null,result);
    );
  ;
  
  const promises = wewant1.map(it => 
     return new Promise((resolve, reject) => 
       getmydata(it, function querydata(err, result) 
         if (err) 
           reject(err);
          else 
           resolve(result);
         
       );
     )
  );

  Promise.all(promises)
  .then(results => 
    //results is a array of the resolved promises
    invoices=results[0];
    accounts=results[1];
    items=results[2];
    organisations=results[3];
    receipts=results[4];
    taxRates=results[5];
    users=results[6];
    trackingCategories=results[7];
    console.log(invoices);
    )
  .catch(err => )
    .then(() => 
        con.end();
    )
)();

【问题讨论】:

【参考方案1】:

将您的数组映射到 Promise,然后使用 Promise.all。这也解决了您未说明的过早关闭连接的问题。

var mysql = require('mysql');

var con = mysql.createConnection(
  host: "10.0.1.103",
  user: "badayaba",
  password: "yadabuba",
  database: "xeroetc"
);




let wewant1 = ["invoices", "accounts", "items", "organisations", "receipts", "taxRates", "users", "trackingCategories"];

function getmydata(sql, result, callback) 
  var query = con.query(sql);
  query.on('result', function(row) 
    callback(null, row);
  );
;

const promises = weweant1.map(it => 
  return new Promise((resolve, reject) => 
    getmydata(sql, it, function querydata(err, result) 
      if (err) 
        reject(err);
       else 
        resolve(result);
      
    );
  )
);

Promise.all(promises)
  .then(results => 
    //results is a array of the resolved promises
  )
  .catch(err => )
  .then(() => 
    // then after catch is a finally block
    con.end();
  )

当然你也可以使用async/await,去掉then的嵌套。您还可以承诺getmydata。不过,它们都使用相同的原则:等待一系列承诺

使用异步/等待

如果getmydata 返回promise 或被声明为async,假设它在async 函数中,则以下sn-p 会执行。干净多了……

const promises = weweant1.map(it => getmydata(sql, it))

try 
  const results = await Promise.all(promises)
 catch (e) 
  // handle error
 finally 
  con.end();

【讨论】:

以上是关于Node.js mysql 结果到数组的主要内容,如果未能解决你的问题,请参考以下文章

Node.js log4j-like 日志系统

如何将mysql的数据行转换为javascript数组? Node.js 应用程序

Node.js Buffer(缓冲区)

带你从零学Node.js

平安产险项目记录

node.js 1