我需要异步使用db.all()
获取所有数据。我不想在回叫中运行其他功能/代码。我想“导出”结果。可以吗?
*我是SQLite的新手*
const sqlite3 = require('sqlite3').verbose()
const db = new sqlite3.Database('./db/subscribers.db')
const createSQLStatement = `CREATE TABLE IF NOT EXISTS subscriptions (id INTEGER PRIMARY KEY AUTOINCREMENT, subscriber TEXT)`
db.run(createSQLStatement)
exports.getAllSubscribers = async () => {
const $sql = `SELECT * FROM subscriptions`
return await db.all($sql, (err, rows) => {
if (err) {
return
}
// I wish to export "rows" which is an array
return rows
})
}
在另一个文件中
const { getAllSubscribers } = require('./foo')
getAllSubscribers().then(subs => {
// subs is not what I expect it to be.
// I'm getting:
// Database { open: true, filename: './db/subscribers.db', mode: 65542 }
// But I do need subs here to loop over and not inside of getAllSubscribers()
})
.catch(e => console.log(e))
我也看过this doc,但似乎没有任何结果能给我带来期望的结果。
答案 0 :(得分:1)
使用then
和catch
时不使用await
。
因此,您需要改进第一个脚本:
const sqlite3 = require('sqlite3').verbose()
const db = new sqlite3.Database('./db/subscribers.db')
const createSQLStatement = `CREATE TABLE IF NOT EXISTS subscriptions (id INTEGER PRIMARY KEY AUTOINCREMENT, subscriber TEXT)`
db.run(createSQLStatement)
exports.getAllSubscribers = () => {
const $sql = `SELECT * FROM subscriptions`
return db.all($sql, []);
}
在另一个文件中,您可以像这样使用await
:
const { getAllSubscribers } = require('./foo')
const getSubscribers = async () => {
const subscribers = await getAllSubscribers();
};
您可以在此处找到更多示例:https://www.scriptol.com/sql/sqlite-async-await.php