javascript - 请帮我解决 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很陌生,现在我对“异步等待”感到非常困惑。
请帮忙。
解决方案
有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”捕获错误。
推荐阅读
- neo4j - neo4j:无法获取数据库“fabric.xxx”的路由表,因为该数据库不存在
- flutter - 想要从设备中获取所选文件的字节数
- javascript - Nuxt:asyncData({ $axios }) 调用在部署中的工作方式与在 localhost 上的工作方式不同
- node.js - Docker - 在已安装的卷上写入常量文件
- c# - 在 PostRequest asp.net 核心中读取正文
- java - Object 类中的静态读/写方法或读/写方法
- python-3.x - 如何使用 np.where 将数据框列填充为其他列值的元组?
- javascript - 循环 Javascript 导入以加载到 VuexORM
- amazon-web-services - 这是解决此问题的正确方法还是我出错了?
- javascript - 从Javascript中的两个数组对象计算唯一值