3

So I'm writing this MySQL select code in node.js. I'm pretty new to js and callback functions, How can I get the var uId from the callback out in the global scope? I'm trying to do this because my function mysqlselect has to return the uId.

function mysqlselect(db, data) {
    let sql = `SELECT id, name FROM users WHERE name = '${data.uName}'`;
    db.query(sql, function (err, result) {
        if (err) throw err;
        let uId = result[0].id;
    });

    // I want to be able to return uId here
};
Yahya
  • 706
  • 8
  • 23
Marco
  • 66
  • 2
  • 10
  • 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) – Henke Feb 26 '21 at 10:37

3 Answers3

3

You can't, because db.query is asynchronous.

You could, however, return a Promise, like so:

function mysqlselect(db, data) {
    return new Promise((resolve, reject) => {
        let sql = `SELECT id, name FROM users WHERE name = '${data.uName}'`;
        db.query(sql, function (err, result) {
            if (err) reject(err);
            let uId = result[0].id;
            resolve(uId);
        });
    });
};

Which you can then use like so:

mysqlselect(db, data).then((id) => console.log(id));
user184994
  • 17,791
  • 1
  • 46
  • 52
1

All queries to databases or requests to an endpoint etc in Javascript are processes asynchronously meaning they will not be executed in the usual course of the execution. Rather these callbacks will be invoked when the process is executed in your case, when the query is done on the database and the repsonse is returned

Now, you can use multiple approaches to deal variables in this scenario but since you wanted to access the variable right after your database query, you can try the below.

Using ASYNC / AWAIT

// YOU CAN USE AWAIT ONLY INSIDE AN ASYNC FUNCTION
async function mysqlselect(db, data) {
    const uIdPromise = return newPromise((resolve, reject) => {
        let sql = `SELECT id, name FROM users WHERE name = '${data.uName}'`;
        db.query(sql, function (err, result) {
            if (err) reject(err);
            resolve(result[0].id);
        });
    })    
    // You can access uId right away here.
    const uId = await uIdPromise;
};

NOTE: If you want to however return this variable and try to access it somewhere you won't be able to do it because an async function will always return a Promise. You would have to either await on an async function or perform a .then

Nandu Kalidindi
  • 6,075
  • 1
  • 23
  • 36
0

Try this:

function mysqlselect(db, data, callback) {
    let sql = `SELECT id, name FROM users WHERE name = '${data.uName}'`;
    db.query(sql, function (err, result) {
        if (err) callback(err, null);
        let uId = result[0].id;
        callback(null, uId);
    });
};

Then you can call it like this:

mysqlselect(db, data, function (err, uId) {
    if (err) throw err;
    console.log(uId)
});
Yahya
  • 706
  • 8
  • 23