Answer the question
In order to leave comments, you need to log in
Promises and database connection, how to work with them correctly?
I have a user object (Member), whose methods work with the database (mysql).
The class itself:
'use strict'
var connection = require('./mysqlconnection');
class Member {
constructor(user) {
console.log('create member...');
this.db = connection();
this.user = user;
this.params = [];
}
loadMember() {
console.log('try to load member...');
let promise = new Promise((resolve, reject) => {
var db = connection();
db.query('SELECT * FROM `pfp_bot_user` WHERE `uid` = '+this.user.id, function(error, rows){
if (error)
reject(new Error(error));
console.log('member loaded...');
if (!rows.length)
reject(new Error('Member not found!'));
resolve(rows);
});
});
return promise;
}
saveMember(user) {
let promise = new Promise((resolve, reject) => {
var row = {
uid : user.id, firstname : user.first_name, lastname : user.last_name, username : user.username
};
var db = connection();
db.query('INSERT INTO `pfp_bot_user` SET ? ', row, function(error, result){
console.log(result);
if (error)
reject(error);
resolve(result);
});
});
return promise;
}
getParam(name) {
if (this.params[name] !== undefined)
return this.params[name];
return null;
}
saveParam(name, value) {
let promise = new Promise((resolve, reject) => {
var row = {
uid : this.user.id, name : name, value : value
};
var db = connection();
db.query('INSERT INTO `pfp_bot_user_values` SET ? ', row, function(error, result){
console.log(result);
if (error)
reject(new Error(error));
resolve(result);
});
});
return promise;
}
loadParams() {
// ...
}
}
module.exports = Member;
'use strict'
var mysql = require('mysql');
var db = null;
function getConnection() {
if (!db || db.state !== 'connected') {
db = mysql.createConnection({
// ...
});
}
db.connect();
return db;
}
module.exports = getConnection;
Answer the question
In order to leave comments, you need to log in
In order not to lose this - use arrow functions, unlike ordinary ones, they use this and arguments from the closure.
If you need to execute several queries in sequence, use a chain of promises:
loadMember() {
return new Promise((resolve, reject) => {
db.query('sql...', (err, result) => {
if(err) {
return reject(err);
}
resolve(result);
}
}).then(result1 => {
return new Promise((resolve, reject) => {
//..
});
});
}
Promise.all([promise1, promise2 /*, ... */]).then(results => {});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question