简体   繁体   English

请帮我解决 JavaScript Asyncronus 问题

[英]Please help me solve JavaScript Asyncronus issue

I have code in connect.js like this我在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;

And I try to call it from insert.js like this我尝试像这样从 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');

However, the result is not what I wanted like below但是,结果不是我想要的,如下所示

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.

What I expected it is should be like我所期望的应该是这样的

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

I'm very new to JavaScript and now I very confuse about 'async-await'.我对 JavaScript很陌生,现在我对“async-await”很困惑。

Please help.请帮忙。

There are callback/Promise/asny,await ways to handle asynchronous有 callback/Promise/asny,await 方式来处理异步

And in the above code, callback and async/await are used in duplicate among the asynchronous handling methods.并且在上面的代码中,回调和async/await在异步处理方法中重复使用。

The callback function works.回调函数有效。

So delete the callback function and run.所以删除回调函数并运行。 [However, the function must support Promise] 【但该函数必须支持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;

if error occrued, then "catch block" catch error.如果发生错误,则“捕获块”捕获错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM