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:

However this works:

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:

With async/await:

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