我正在开发一个rethinkDB数据库,并使用快速服务器和HTTP请求访问它。
从数据库中获取数据然后将其响应到HTTP请求需要,据我所知,这是一个异步函数。
我看起来像那样:getChain(notNeeded, callback) {
// Connecting to database
let connection = null;
rethinkdb.connect({ host: 'localhost', port: 28015 }, (err, conn) => {
if (err) throw err;
connection = conn;
rethinkdb.db(dbUsed).table(tableUsed).run(connection, (err, cursor) => {
if (err) throw err;
cursor.toArray((err, result) => {
if (err) throw err;
// console.log(JSON.stringify(result, null, 2));
console.log(result + "1");
callback(result);
})
})
})
}
我正在通过以下方式访问它:
router.get('/', (req, res, next) => {
DatabaseBlockchain.getChain(('not needed'), callback => {
res.status(200).json(callback);
})
})
正如您所看到的,有一个变量"不需要",我不需要。
但是在创建" getChain"如果没有那个第二个变量,我就无法调用"回调(结果)"最后得到错误"回调不是函数"。
答案 0 :(得分:1)
您必须从函数定义和函数调用中删除“not needed”参数:
getChain(callback) {
和
DatabaseBlockchain.getChain(result => {
res.status(200).json(result);
})
答案 1 :(得分:1)
是的,那是可能的。回调的行为与其他所有参数一样。
getChain(callback) {
// Connecting to database
let connection = null;
rethinkdb.connect({ host: 'localhost', port: 28015 }, (err, conn) => {
if (err) throw err;
connection = conn;
rethinkdb.db(dbUsed).table(tableUsed).run(connection, (err, cursor) => {
if (err) throw err;
cursor.toArray((err, result) => {
if (err) throw err;
// console.log(JSON.stringify(result, null, 2));
console.log(result + "1");
callback(result);
})
})
})
}
然后调用它
router.get('/', (req, res, next) => {
DatabaseBlockchain.getChain(callback => {
res.status(200).json(callback);
})
})
有些事情需要注意: