Skip to content
Advertisement

Why can’t I use a local variable after a SQL query in Node.js?

I have to select all tags available in the database, so I could use them in my function, but I can’t use the variable after I assigned a value to the variable in the callback function of the query, why?

Code which is not working:

    let tags = [];
    db.query(
      `select * from tags`,
      (err, results) => {
        tags = results;
      } 
    )
    console.log(tags);
    return;

However this works:

    let tags = [];
    db.query(
      `select * from tags`,
      (err, results) => {
        tags = results;
        console.log(tags);
      } 
    )
   return;

but why? I want to use the variable tags after that query again, but somehow the value assigned to it is destroyed after the query. What would I have to change?

Advertisement

Answer

Javascript is asynchronous language, db.query is a network call which will be asynchronous, so if you want to use the response of the query it has to be called after the db.query is executed.

In the first case console.log(tags); runs before db.query is executed and you are getting undefined response.

In the second case console.log(tags); runs after db.query is executed thats why you are getting the response from the query.

You use this using Promise:

async function queryExec() {

    let tags = await promiseQuery(`select * from tags`);
    console.log(tags);
    return tags;
}

function promiseQuery(query) {
    return new Promise((resolve, reject) => {
        db.query(query, (err, results) => {
            if (err) {
                return reject(err);
            }
            resolve(results);
        })
    })
}

With async/await:

async function queryExec() {

    let tags = await db.query(`select * from tags`);
    console.log(tags);
    return tags;
}

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement