Answer the question
In order to leave comments, you need to log in
How can I implement the output of the ID from the database to a variable?
pool.getConnection(function(err, connect) {
connect.query('SELECT * FROM users WHERE vkontakteid = ?', [req.user.id], function(err, result) {
if (err) console.log(err);
else {
if (result.length === 0) {
const data = [req.user.id, req.user.displayName]
connect.execute('INSERT INTO users (vkontakteid, name) VALUES (?,?)', data)
console.log('Вы были зарегистрированы')
} else {
const data = [req.user.displayName, req.user.id];
connect.execute('UPDATE users SET name=? WHERE vkontakteid=?', data)
console.log('Такой пользователь уже существует')
console.log(result)
}
}
}, pool.releaseConnection(connect))
})
res.redirect('/')
Answer the question
In order to leave comments, you need to log in
You can just create a variable before calling getConnection
let id;
pool.getConnection(function(err, connect) {
connect.query(..., function(err, result) {
...
if(!err && result.length !== 0) {
id = result.id;
}
...
}
}
function createOrUpdateUsersCallback(err, result) {
if (err) {
console.log(err);
}
else {
// Use result.id as you want
}
}
function createOrUpdateUsers(callback) {
pool.getConnection(function(err, connect) {
connect.query(..., function(err, result) {
if(err) {
callback(err, null);
}
else {
// Do create or update
callback(null, result);
}
}
}
}
createOrUpdateUsers(createOrUpdateUsersCallback);
const createOrUpdateUsersPromise = new Promise((resolve, reject) => {
function createOrUpdateUsers(callback) {
pool.getConnection(function(err, connect) {
connect.query(..., function(err, result) {
if(err) {
reject(err);
}
else {
// Do create or update
resolve(result);
}
}
}
}
})
const result = await createOrUpdateUsersPromise();
const id = result.id;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question