4

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

3 Answers 3

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));
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.