问题描述
按照官方文档运行简单代码,但是报错
const r = require('rethinkdb');
var connection = null;
r.connect( {host: 'localhost',port: 28015},function(err,conn) {
if (err) throw err;
connection = conn;
})
// r.dbCreate("blog").run(connection,result) {
// if (err) throw err;
// console.log(result);
// });
r.db('test').tableCreate('authors').run(connection,result) {
if (err) throw err;
console.log(JSON.stringify(result,null,2));
})
未处理的拒绝 ReqlDriverError:run
的第一个参数必须是打开的连接。
在 ReqlDriverError.ReqlError [作为构造函数] (/Users/tejastank/source/electronjs/website-scanner/node_modules/rethinkdb/errors.js:23:13)
在新的 ReqlDriverError (/Users/tejastank/source/electronjs/website-scanner/node_modules/rethinkdb/errors.js:68:50)
在 Function.TermBase.run (/Users/tejastank/source/electronjs/website-scanner/node_modules/rethinkdb/ast.js:133:29)
在 HTMLButtonElement。 (file:///Users/tejastank/source/electronjs/website-scanner/index.js:59:41)
(节点:45504)[DEP0005] 弃用警告:由于安全和可用性问题,不推荐使用 Buffer()。请改用 Buffer.alloc()、Buffer.allocUnsafe() 或 Buffer.from() 方法。
解决方法
connection
填充在 .connect()
回调中,不能保证在调用后完全可用。您需要在回调中工作:
const r = require('rethinkdb');
r.connect( {host: 'localhost',port: 28015},function(err,conn) {
if (err) throw err;
r.db('test').tableCreate('authors').run(conn,result) {
if (err) throw err;
console.log(JSON.stringify(result,null,2));
});
});
或者通过使用承诺:
const r = require('rethinkdb');
r.connect({host: 'localhost',port: 28015})
.then(function(conn) {
return r.db('test').tableCreate('authors').run(conn);
})
.then(function(result) {
console.log(JSON.stringify(result,2));
});