如何解决如何连续使用数据
我试图弄清楚如何将sqlite与Node JS一起使用。当我问数据库想要什么时,我不知道如何使用行。我在网上无处不在,但没人能真正解释获取完成后如何使用该行。
我的意思是它返回该行,但我不能使用它。
const sqlite3 = require('sqlite3').verbose();
// open the database
let db = new sqlite3.Database('./db/chinook.db');
let sql = `SELECT PlaylistId id,Name name
FROM playlists
WHERE PlaylistId = ?`;
let playlistId = 1;
// first row only
var test = db.get(sql,[playlistId],(err,row) => {
if (err) {
return console.error(err.message);
}
return row
? console.log(row.id,row.name)
: console.log(`No playlist found with the id ${playlistId}`);
});
//What I added to try to use the row after the get is done
console.log(test.id) // I get "undefined" here. How are we really suppose to do it?
// close the database connection
db.close();
此代码来自here
解决方法
尝试使用Promise,例如:
const query = new Promise((resolve,reject) => {
var test = db.get(sql,[playlistId],(err,row) => {
if (err) {
reject(err);
}
resolve(row);
});
});
query
.then(data => console.log(data))
.catch(err => console.log(err));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。