我一直在慢慢学习node.js,这样我就可以更好地集成我们当前的许多ops(mysql)和xero会计。
我在mysql中有几个表,每个表对应[“invoices”,“accounts”,“items”,“organizations”,“receipts”,“taxrate”,“users”,“trackingcategories”],每个表都有一个json列,其名称与其所在的表相同。这不是一个json问题。
从“+wewant1[i]”发送类似“select”+wewant1[i]+“的查询基本上是简单的“select invoices from invoices”,并且易于迭代。
我可以得到要列出的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谢谢steven!我想我明白了:
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条答案
按热度按时间ltskdhd11#
将数组Map到promises,然后使用
Promise.all
. 这也解决了过早关闭连接的问题。当然你也可以用
async
/await
把这些东西扔掉then
筑巢。你可以另外承诺getmydata
. 不过,它们都使用相同的原则:等待一系列承诺。使用异步/等待
如果
getmydata
返回一个promise
或者被宣布async
,下面的代码段就可以了,假设它位于async
功能。干净多了。。。