-1

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?

Opat
  • 93
  • 1
  • 2
  • 9
  • Area of visibility? – KeyGenQt Sep 26 '20 at 13:09
  • Hey, I don't know what you mean. I have posted the whole code. – Opat Sep 26 '20 at 13:13
  • I think the variable is not assigned because a copy is being created. This can be seen in many languages. It may also be due to asynchronous. – KeyGenQt Sep 26 '20 at 13:17
  • 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) – jonrsharpe Sep 26 '20 at 13:35

2 Answers2

0

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;
}
aRvi
  • 2,203
  • 1
  • 14
  • 30
  • And what would be the solution? I can't use await before the query because I get the error that await is only valid for async functions. – Opat Sep 26 '20 at 13:13
  • 2nd statement is correct you can use that, you will get a response from callback function – aRvi Sep 26 '20 at 13:14
  • if you want to use async/await the function should be like `async function queryExec() {` – aRvi Sep 26 '20 at 13:14
  • but I need the variable ```tags``` after the query. I need to await somehow until the query is finished but how? The await keyword does not work if I try to use it – Opat Sep 26 '20 at 13:17
  • @Opat I have updated the answer, you can promise using that and the use async/await – aRvi Sep 26 '20 at 13:23
  • Hey, could you just help me to write it without separate functions? So to say inline code? Then I will mark you answer, because somehow I tried it with Promises but it didnt work – Opat Sep 26 '20 at 13:32
0

Query is an async function, so the value hasnt returned by the time you try to print it. within the callback function however, you already have the return value you expect. If you need it to run synchronously you could await the query function, and have the value in hand.

If you set your function be async then you will be able to await the result. something like:

const foo = async () => {
    let tags = [];
    tags =  await db.query(
      `select * from tags`
    );
    console.log(tags);
    return;
}
audzzy
  • 721
  • 1
  • 4
  • 12