0

The variable I declared in my function only updates while being inside the database sub-function, as soon as the program leaves the sub-function, the variable remains at the value it was declared.

I've been trying to retrieve information from my database and display it on my website. What I am retrieving is the amount of rows that every single one of my tables contain.

  let description = 'abc';

  for (const keyType of keyTypes) {
    db.get(getKeyCount(keyType.name), function (err, row) {
      if (err) {
        console.error(err.message);
      }
      let count = JSON.parse(JSON.stringify(row))["COUNT(*)"];
      description += blockQuote(keyType.name) + ' ' + codeBlock(count) + '\n';
      console.log(description); #INSIDE
    });
  }

  console.log(description); #OUTSIDE

When I am inside my keyTypes loop, my description variable updates accordingly: (view #INSIDE for reference)

abc
abc> KEY_1 `2`

abc> KEY_1 `2`
> KEY_2 `0`

abc> KEY_1 `2`
> KEY_2 `0`
> KEY_3 `0`

abc> KEY_1 `2`
> KEY_2 `0`
> KEY_3 `0`
> KEY_4 `0`

abc> KEY_1 `2`
> KEY_2 `0`
> KEY_3 `0`
> KEY_4 `0`
> KEY_5 `0`

The second I leave the keyTypes loop, I get this for description: (view #OUTSIDE for reference)

abc

At first I thought it was a scope issue, so I changed my variable type from let to var, but it still doesn't work. I'm lost at this point, any help is more than appreciated.

  • The code inside your callback function `function (err, row)` doesn't execute until later, much later than `console.log(description); #OUTSIDE` – James Mar 17 '23 at 21:42

0 Answers0