[英]How would I pass down a value to another function with nodejs?
So, I am trying to make a thing with discord js and sqlite3 but I've been stuck on this one issue for the past few hours and I still do not understand how I would resolve it.所以,我试图用 discord js 和 sqlite3 做一件事,但在过去的几个小时里我一直被困在这个问题上,我仍然不明白我将如何解决它。
client.countDB = function(discordID) {
const arr = [];
db.each(`SELECT count(DiscordID) FROM verification WHERE DiscordID = ${discordID}`, function(err, row){
if(err){console.log(err); return 0;}
arr.push(Object.values(row))
return arr;
})
return arr[0];
};
So I am trying to get data that is only available in db.each
but I do not know how I would pass it out so I can return the expected value.因此,我试图获取仅在
db.each
可用的数据,但我不知道如何将其传递出去,以便返回预期值。 I've already tried using global variables, putting it in a larger scope, and I still cannot figure out how to do it.我已经尝试使用全局变量,把它放在更大的范围内,但我仍然不知道如何去做。
Sorry if I am confusing I'm not used to asking questions all the time.对不起,如果我感到困惑,我不习惯一直提问。
Edit: Should have said I'm using the npm sqlite3 module.编辑:应该说我正在使用npm sqlite3模块。 https://www.npmjs.com/package/sqlite3
https://www.npmjs.com/package/sqlite3
wrap your code in a function to make it synchronous, reference将您的代码包装在一个函数中以使其同步,参考
var deasync = require('deasync');
function syncFunc()
{
let arr;
client.countDB = function(discordID) {
db.each(`SELECT count(DiscordID) FROM verification WHERE DiscordID = ${discordID}`, function(err, row){
if(err){console.log(err); arr = null;return;}
const tmp = []
tmp.push(Object.values(row))
arr = tmp;
})
};
while((arr === undefined))
{
deasync.runLoopOnce();
}
return arr[0];
}
If you have data in query easiest way to do is using promise.如果您有查询中的数据,最简单的方法是使用 promise。
client.countDB = function(discordID) {
return new Promise((resolve, reject) => {
db.each(`SELECT count(DiscordID) FROM verification WHERE DiscordID = ${discordID}`, function(err, row){
//if you want to throw as an error, reject promise with the incoming error as "reject(err)"
if(err){console.log(err); return resolve(0);}
arr.push(Object.values(row))
return resolve(arr[0]);
})
})};
// You can use this as
client.countDB('someId')
.then(data => console.log(data))
.catch(err => console.log(err));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.