UnhandledPromiseRejectionWarning: TypeError: dba.run is not a function

时间:2021-01-02 01:59:41

标签: javascript node.js sqlite asynchronous

enter image description here

我正在使用 node 和 sqlite,尝试使用 sqlite-async 节点模块(https://github.com/fhellwig/sqlite-async/blob/master/sqlite-async.js)异步连接到数据库。

我有以下功能:

const Database = require('sqlite-async');

async function asyncdb() {
const dba = new Database;
return await dba.open('./test.db').then(() =>
    console.log('async db opened')
  )
  .catch(err => {
    console.log('async db failed');

  })

}

和:

async function select_from_table(dba,tablename, limit) {

  let arr = [];
  let sql = `SELECT Id FROM ${tablename} WHERE Type='Real' LIMIT ${limit}`;
  return await dba.run(sql);
}

当我像截图一样运行它们时:

$ node sqlite.js 

(node:12943) UnhandledPromiseRejectionWarning: TypeError: dba.run is not a function
at select_from_table (/home/optionhomes11/nodeprojects/hayes/sqlite.js:113:20)
at Object.<anonymous> (/home/optionhomes11/nodeprojects/hayes/sqlite.js:141:1)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
at internal/main/run_main_module.js:17:47
(node:12943) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error 
originated either by throwing inside of an async function without a catch block, or by 
rejecting a promise which was not handled with .catch(). To terminate the node process 
on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see 

我该如何解决这个问题?

编辑:

将代码更改为:

const dba = asyncdb();
console.log('out',dba);

给出:

out Promise { <pending> }
async db opened

编辑2:

谢谢,但我收到了这样的语法错误

console.log('async db opened');
                             ^

SyntaxError: missing ) after 参数列表

使用您的函数版本。我也试过等待,但它不允许它在那里说它必须在异步函数中

enter image description here

1 个答案:

答案 0 :(得分:3)

您没有根据 documentation example

.then() 上处理返回的数据库

我认为以下应该有效

const Database = require('sqlite-async');

async function asyncdb() {
const dba = new Database;
return await dba.open('./test.db').then((db) => {
    console.log('async db opened');
    return db;
  })
  .catch(err => {
    console.log('async db failed');
  })
}

当您调用 asyncdb 函数时,您也不是在等待它

const dba = await asyncdb();
console.log('out',dba);