使用Node.js进行简单的参数化sqlite查询

时间:2018-07-20 12:15:32

标签: node.js sqlite

在以下代码中运行查询时,errnull,而row未定义。我知道那排在那里。

我有这个:

const db = new sqlite3.Database('./state.sqlite');

const hasBeenProcessed = (messageId) => {
    return new Promise((resolve, reject) => {
        try {
            db.get('SELECT id FROM messages WHERE id = ?', [messageId], (err, row) => {
                if (err) {
                    reject(err);
                    return;
                }
                resolve(row != null);
            });
        }
        catch (err) {
            reject(err);
        }
    });
}

hasBeenProcessed(100)
    .then(result => {
        console.log(`Response was ${result}`);
    })
    .catch(err => {
        console.log(err);
    });

1 个答案:

答案 0 :(得分:0)

只是一个建议。我承诺所有回调类型的函数。只是使代码更易于推理,保持一致等,等等。看是否可行:

const { promisify } = require('util');

const db = new sqlite3.Database('./state.sqlite');

db.get = promisify(db.get);

const hasBeenProcessed = async (messageId) => db.get('SELECT id FROM messages WHERE id = ?', [messageId]);

hasBeenProcessed(100)
    .then(row => {
        console.log(`Response was ${row}`);
    })
    .catch(err => {
        console.log(err);
    });