I am working on a NodeJs server and I am implementing a Sqlite3
database.(我正在使用NodeJs服务器,正在实现Sqlite3
数据库。)
My problem is that the "saveMddToDb" method starts before the "createMddTables" method is finished.(我的问题是“ saveMddToDb”方法在“ createMddTables”方法完成之前开始。)
So I would like to know how to wait until the end of the first one before starting the second one.(所以我想知道如何等到第一个开始之后再开始第二个。)
const db = require('./db.js');
const myDb = new db(configServer.dataBase.useDatabase === true ? configServer.dataBase.name : null);
myDb.createMddTables();
myDb.saveMddToDb(dataModel);
class Db {
constructor(name) {
this.db = new sqlite3.Database(name === null ? ':memory:' : name, err => {
if (err) {
return console.error(err.message);
}
console.log(colors.yellow(`Connected to the ${name === null ? 'memory' : name} SQlite database`));
});
}
close() {
this.db.close(err => {
if (err) {
return console.error(err.message);
}
console.log(colors.yellow('Close the database connection'));
});
};
createMddTables() {
this.createTableContacts();
};
createTableContacts() {
const sql = `CREATE TABLE IF NOT EXISTS contacts (
id TEXT PRIMARY KEY,
firstName TEXT NOT NULL,
lastName TEXT NOT NULL,
nickName TEXT NOT NULL,
profilePicture BLOB)`;
this.db.run(sql, err => {
if (err) {
return console.log(err.message);
}
console.log(colors.yellow('Table contacts created'));
});
};
saveMddToDb(mddJson) {
if(mddJson) {
const sqlContacts = `INSERT OR IGNORE INTO contacts VALUES (?, ?, ?, ?, ?)`;
mddJson.contacts.forEach(contact => {
this.db.run(sqlContacts, [uuidv4(), contact.firstName, contact.lastName, contact.lastName, contact.profilePicture], err => {
if (err) {
return console.log(err.message);
}
console.log(colors.yellow('Contacts added to database'));
});
});
}
}
};
module.exports = Db;
ask by GuillaumeF translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…