1
var result;

function getName(id) {
    //Detect XP
    connection.query(`SELECT name FROM users WHERE id = "${id}"`, function (err, rows, fields) {
        if (err) console.log(err);
        result = rows[0].name;
    });

    console.log(result);
}

I want to access the result variable from ouside of the mysql query function. It is defined outside of all functions but the console.log still outputs undefined . How can I access it?

KarelRuzicka
  • 461
  • 2
  • 13
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – tkausl Dec 29 '20 at 17:14

1 Answers1

3

Not to mention that you're exposing your code to potential SQL injections, you are handling it improperly. Mysql module is not synchronous and will always execute after console.log (in your example).

There are two things that you can do:

  1. Use a module that supports async operations (Knex, for example)
  2. Wrap your code in a promise and execute it asynchronously.

The second example is quite easy to implement. I'll also fix the sql injection part and limit the output to 1;

function getName(id) {
    return new Promise(function(resolve, reject) {
        connection.query("SELECT name FROM users WHERE id = ? LIMIT 1", [id], function (err, rows, fields) {
            if (err) return reject(err);
            resolve(rows[0].name);
        });
    });
}

To run this code, you can use an async/await approach or a promise-based one.

// Async/await:

(async function(){
    let name = await getName(1);
    console.log(name);
})();


// Promise based:

getName(1).then(function(name) {
    console.log(name);
})

Edit:

Knex would make it really easy:

function getName(id) {
    return knex.select('name').from('users').where(id,1).limit(1).first();
}

Run it either with async/await or as a promise.

Ringolds
  • 236
  • 1
  • 8