H
H
hatealleverything2020-07-07 08:06:28
MySQL
hatealleverything, 2020-07-07 08:06:28

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('/')


5f040e3cd7d6b618025262.jpeg

Is it possible to somehow output this id to a variable?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Edrets, 2020-07-07
@ElijahCapricorn

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;
        }
        ...
    }
}

But due to the fact that queries to the database are asynchronous, you will not be able to find out when the value is written to the variable.
For this reason, a callback is passed to asynchronous functions, which will receive the result of executing asynchronous code as input.
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);

But in the modern world, the easiest way to work with asynchronous code is through promises and async / await
. On promises, it will be something like
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 question

Ask a Question

731 491 924 answers to any question