我之前曾尝试将此代码包装在回调中,异步该语言必须提供的任何内容。然而,我仍然一事无成。
问题是,成员仍然是空的,即使应该用信息推送它。 然而, channel 工作正常。
奇怪的是
console.log(values);
在
之前打印console.log(result);
有趣的是,
console.log(result)
确实有正确的数据,但我在哪里
console.log(members)
它是空的。
我已经测试过,查询都是正确的,这实际上是在当前返回之前推送和获取结果的问题(我认为 Promises 意味着事情会更加有序,但也许我的理解是错误的)。
完整代码如下:
module.exports.controller = (query, helper, cache, Database, mysql, config) => {
return async (req, res) => {
let zone = req.body.zone;
let returning = {};
if(!zone){
return res.json(helper.responseJson(false, 'Missing parameter "zone"'));
}
function teleport_available(channel_name){
if(channel_name.indexOf("Nadaj / Usuń") === -1){
return true;
}else{
return false;
}
}
await mysql.query("SELECT * FROM flamespeak_pbot.zones WHERE zone = '"+ zone +"'", async (err, row) => {
if (err) throw err;
row = row[0];
if (row.length == 0) {
return res.json(helper.responseJson(false, "Zone not found."));
} else {
var channelsPromise = new Promise((resolve, reject) => {
const channels = [];
JSON.parse(row.assignGroupAdditional_ch).forEach(additionalCh => {
cache.channelList.filter(channel => channel.cid == additionalCh).forEach(mainCh => {
mainCh.propcache.teleport_available = teleport_available(mainCh.propcache.channel_name);
mainCh.propcache.subchannels = [];
cache.channelList.filter(channel => channel.pid == additionalCh).forEach(subCh => {
subCh.propcache.teleport_available = teleport_available(mainCh.propcache.channel_name);
mainCh.propcache.subchannels.push(subCh);
});
channels.push(mainCh.propcache);
});
});
resolve(channels);
});
var membersPromise = new Promise((resolve, reject) => {
let members = [];
query.serverGroupClientList(row.serverGroupID)
.then(serverGroupList => {
serverGroupList.forEach(member => {
var sql = "SELECT * FROM teamspeak_clientDbList WHERE client_database_id = '" + member.cldbid + "'";
mysql.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
members.push(result);
})
});
})
.then(() => {
console.log(members);
resolve(members);
});
});
}
Promise.all([channelsPromise, membersPromise]).then(function(values) {
console.log(values);
returning = {
'channels' : values[0],
'members' : values[1],
'pbot' : row,
};
res.send(helper.responseJson(true, returning));
});
});
};
};
最佳答案
恕我直言,回调、 promise 和异步/等待的混合非常难以理解。你应该明智地简化它。 (或者冒着你的名字被稍后必须维护此代码的人诅咒的风险。)
只要 MySQL 需要(无论查询完成或失败),第二个 mysql.query() 方法中的回调就会被调用。但是您不会解析该回调代码中异步方法的任何 promise 或返回。因此,您的 console.log(result)
显示正确的结果,但您的其他代码无法访问该结果;您的 Promise.all 在调用该方法之前解析。
一般来说,这样的事情是正确的做法:
var sql =
"SELECT * FROM teamspeak_clientDbList WHERE client_database_id = '" +
member.cldbid + "'";
mysql.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
members.push(result);
resolve (result); // <<< add this line
})
但在你的情况下它可能不起作用:你的函数 query.serverGroupClientList()
似乎返回一个 Promise。您没有向我们展示该函数,因此很难猜测如何将其编织到您的逻辑中。
关于mysql - 数组推送在 Promise Node.js 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58955262/