节点等待sqlite返回结果

时间:2019-03-07 22:55:08

标签: node.js sqlite

我从Python刚接触Node,所以我习惯于按照我编写代码的顺序执行代码,这让我有些困惑。

我基本上是从SQLite数据库取回行,并对每行执行一个操作,然后保持运行总计。然后,我希望最终总数能回复用户(这是Discord机器人)

我试图将我的代码包装在Promise中,但是当它运行时,我的机器人崩溃了,提示“未定义查询”。

async function feelingCommand(username,receivedMessage){
let sqlStatement = `SELECT Message FROM discord WHERE User = ? ORDER BY Time DESC LIMIT 2`;
let total = 0;
const query = await new Promise((resolve,reject) => {
    db.run(sqlStatement, (err) => {
    if(err) {
        return console.log(err.message);
        reject(err); 
    }
    db.each(sqlStatement, [username], (err, row) => {
        if (err) {
          reject(err);
        }
        let score = sentiment.analyze(`${row.Message}`).comparative;
        total = total + score;

      });
      resolve(query);
});
});
console.log(total)

}

如果能为我指明正确的方向,我将不胜感激。老实说,我很惊讶我走了这么远:)

1 个答案:

答案 0 :(得分:0)

好吧,我的附加搜索表明db.each难以实现,因此我转而使用db.all和带有答应的foreach循环

async function feelingCommand(username,receivedMessage){
let sqlStatement = `SELECT Message FROM discord WHERE User = ? ORDER BY Time DESC LIMIT 2`;
let total = 0;
const query = await new Promise((resolve,reject) => {
    db.all(sqlStatement, [username], (err, rows) => {
        if (err) {
          reject(err);
        }
        rows.forEach((row) => {
            console.log(row.name);
            let score = sentiment.analyze(`${row.Message}`).comparative;
            total = total + score;
      });
      resolve(total);
    });
})