请帮助我解决JavaScript异步问题



我在connect.js中有类似的代码

const sqlite3 = require('sqlite3').verbose();
class Connection {
  static connect() {
    let db = new sqlite3.Database('../SQlite-tester-001/db/sqlite_tester001.db', sqlite3.OPEN_READWRITE, (err) => {
      if (err) {
        console.error(err.message);
      }
      else {
        console.log('Connected to the tester database.');
      }
    });
    return db
  }
}
module.exports = Connection;

我试着从insert.js中调用它,就像这个一样

const Connection = require('./connect');
(async () => {
    let db = await Connection.connect();
    await console.log('This line is below Connection.connect()');
})();
console.log('This line is below Async function');

然而,结果并不是我想要的

wittinunt@Wittinunt-VCIS-PC:~/GitHub/SQlite-tester-001$ node insert.js
This line is below Async function
This line is below Connection.connect()
Connected to the tester database.

我所期望的应该是

Connected to the tester database.
This line is below Connection.connect()
This line is below Async function

我对JavaScript非常陌生,现在我对"异步等待"非常困惑。

请帮忙。

有回调/Promise/asny,等待处理异步的方法

在上面的代码中,回调和async/await在异步处理方法中重复使用。

回调函数起作用。

因此,删除回调函数并运行。【但是,该功能必须支持Promise】

const sqlite3 = require('sqlite3').verbose();
class Connection {
  static async connect() {
    try {
      let db = await new sqlite3.Database('../SQlite-tester-001/db/sqlite_tester001.db', sqlite3.OPEN_READWRITE);
      console.log('Connected to the tester database.');
    } catch (err) {
      console.error(err.message); 
    }
  }
}
module.exports = Connection;

如果出现错误,则";捕获块";catch错误。

最新更新