Answer the question
In order to leave comments, you need to log in
How to implement asynchronous queries to the database in Express.js ( MySql )?
Good afternoon. Faced such a problem. There is a condition, if such an identifier already exists in the database, then we will update the name in this line. If there is no such identifier, then we will add an identifier and a name. I was able to implement it, but when I started testing and logging in and out of my account, I constantly got an error (Database connection closed). I realized that it was impossible to do without asynchronous requests, I began to understand Promise, but the problem remained. Can't find good documentation on Promises or any video. Could you tell me how this can be implemented and where the errors are, or suggest a good source on promises for Express.js. With the exception of Metanit, I read the article about pool, but I could not find an answer to my question.
Here's what I managed to sketch in order to do it at all.
// pool.query('SELECT * FROM users WHERE vkontakteid = ?', [req.user.id])
// console.log('Подключение к бд успешно, условие выполнено')
// results.length === 0
// const data = [req.user.id, req.user.displayName]
// pool.execute('INSERT INTO users (vkontakteid, name) VALUES (?,?)', data)
// console.log('Данные добавлены')
// const data = [req.user.displayName, req.user.id];
// pool.execute('`UPDATE users SET name=? WHERE vkontakteid=?`', data)
// console.log('Данные обновлены')
if (result.lenght === 0)
pool.query('SELECT * FROM users WHERE vkontakteid = ?', [req.user.id], console.log('Подключение к бд успешно, условие выполнено'))
.then(result => {
if (result.lenght === 0) {
const data = [req.user.id, req.user.displayName]
return pool.execute('INSERT INTO users (vkontakteid, name) VALUES (?,?)', data, console.log('Данные добавлены'))
} else {
const data = [req.user.displayName, req.user.id];
return pool.execute('UPDATE users SET name=? WHERE vkontakteid=?', data, console.log('Данные обновлены'))
}
})
.then(result => {
console.log(result[0]);
pool.end();
})
.then(() => {
console.log("пул закрыт");
})
.catch(function(err) {
console.log(err.message);
});
Answer the question
In order to leave comments, you need to log in
Specifically, this task is solved through https://dev.mysql.com/doc/refman/8.0/en/insert-on-...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question