sqlite.get()导致TypeError:无法读取属性'get'null
当试图执行一个sql.get()调用它在一些地方工作,但在其他地方,我似乎无法弄清楚有什么区别。
数据库成功打开或至less我从来没有得到一个错误,它永远不会被closures。 我也在第二个(工作示例)中使用Discord.js,不知道是否相关。
在这个例子中,它不起作用。
test.js:
const sql = require("sqlite"); sql.open("./data.sqlite"); exports.getItemID = function(item) { return new Promise(function (fulfill, reject){ sql.get(`SELECT * FROM items WHERE name="${item}"`).then(row => { console.log(`do stuff`); }).catch((e) => { console.error; reject(e); }) }); } exports.getItemID("Coins").then(itemID => { console.log(itemID); }).catch((e) => { console.log(e); });
堆栈跟踪:
$ node test.js TypeError: Cannot read property 'get' of null at Promise (/Users/julianveerkamp/node_modules/sqlite/main.js:225:18) at Promise (<anonymous>) at Database.get (/Users/julianveerkamp/node_modules/sqlite/main.js:224:12) at /Users/julianveerkamp/workspace/test-bot/test.js:6:13 at Promise (<anonymous>) at Object.exports.getItemID (/Users/julianveerkamp/workspace/test-bot/test.js:5:12) at Object.<anonymous> (/Users/julianveerkamp/workspace/test-bot/test.js:15:9) at Module._compile (module.js:573:30) at Object.Module._extensions..js (module.js:584:10) at Module.load (module.js:507:32)
但是当我调用一个函数
const sql = require("sqlite"); sql.open("./data.sqlite"); // other stuff let commandFile = require(`./commands/command.js`); commandFile.run(client, message, args); // other stuff
它工作得很好。
command.js:
const sql = require("sqlite"); sql.open("./data.sqlite"); exports.run = (client, message, args) => { sql.get(`SELECT * FROM scores WHERE userID ="${message.author.id}"`).then(row => { // Do stuff with row }).catch(() => { console.error; }); }
这可能是一个在sqlite
的bug,所以我继续使用sqlite3
来代替,并用util.promisify()来包装/ promisified函数。
const util = require('util'); const sqlite3 = require('sqlite3'); var db = new sqlite3.Database('./data.sqlite'); db.get = util.promisify(db.get); db.run = util.promisify(db.run); exports.getItemID = function(item) { return new Promise(function (fulfill, reject){ db.get(`SELECT * FROM items WHERE name="${item}"`).then(row => { console.log(`do stuff`); }).catch((e) => { console.error; reject(e); }); }); } exports.getItemID("Coins").then(itemID => { console.log(itemID); }).catch((e) => { console.log(e); });
注意:函数内部的新Promise没有必要。 我们可以从get函数返回promise。
- 即使用户重新加载页面,如何保持function运行
- 从Express JS发送自定义错误消息到Backbone
- 如何从PHP脚本给Node.js服务器一个命令?
- 是否有像node.js一样的MediaWiki模块?
- Socket.io – 客户端断开后手动重新连接
- 在SystemJS加载器环境中将相对path映射到绝对path的方法
- 通过Node.js Ajax服务Javascript文件的正确方法?
- Promise findOneAsync variable = {“isFulfilled”:false,“isRejected”:false}?
- debuggingJavascript和潜入Nodejs c + +代码