0

So I have a database with SQLite and I'm happy but when I try to output a value into a local variable I receive this error:

console.log(UserMurderCoins);
ReferenceError: UserMurderCoins is not defined

My Code:

sql.get(`SELECT * FROM monney WHERE userId ="${message.author.id}"`)
   .then(row => {var UserMurderCoins = row.coins});

console.log(UserMurderCoins);
Dan
  • 59,490
  • 13
  • 101
  • 110
Dillgo
  • 73
  • 2
  • 2
  • 6
  • 1
    `sql.get` is an asynchronous function. `row => {var UserMurderCoins = row.coins}` is executed later than `console.log(UserMurderCoins);`. Also the scope of the variable is the function body. – Lemix Sep 29 '18 at 19:52
  • Read more of asynchronous programming (e.g. first google link: https://dev.to/siwalik/async-programming-basics-every-js-developer-should-know-in-2018-a9c ) – Lemix Sep 29 '18 at 20:00

1 Answers1

2

As @Lemix said in comment, sql.get is an async function and the console.log would be executed before it is done.

Also be aware of the variable scope. var UserMurderCoins is defined inside a then function and is accessed out of the scope. So, it wouldn't be defined even if the statement was executed after the sql.get.then.

you can either run the console.log inside the then function or define the variable globally and only assign it inside the then function.


UPDATE:

To be more comfortable with promises, you can use async await syntax.

I modified your code with a little changes to be working.

async function f() {
var UserMurderCoins = (await sql.get(`SELECT * FROM monney WHERE userId ="${message.author.id}"`)).coins;

console.log(UserMurderCoins);
}

f();
  • So, how do I declare the variable globally ? And will declaring it globally will allow me to put the console.log() outside of the .then function ? – Dillgo Sep 30 '18 at 06:51
  • you can write `var UserMurderCoins;` before `sql.get` but because your `sql.get` function is a promise you still will have problem. I will update the answer to contain a working code soon. – Amir Masud Zare Bidaki Sep 30 '18 at 07:11