Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a variable from a callback function in Javascript

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
};
like image 729
Marco Avatar asked Sep 18 '25 05:09

Marco


2 Answers

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));
like image 195
user184994 Avatar answered Sep 19 '25 20:09

user184994


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

like image 20
Nandu Kalidindi Avatar answered Sep 19 '25 19:09

Nandu Kalidindi