首页 > 解决方案 > 请帮我解决 JavaScript Asyncronus 问题

问题描述

我在 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很陌生,现在我对“异步等待”感到非常困惑。

请帮忙。

标签: javascriptasynchronousasync-await

解决方案


有callback/Promise/asny,await方式处理异步

并且在上面的代码中,callback 和 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 block”捕获错误。


推荐阅读