-1

I´m using a function to grab data from a database and store those into a array. This array should now be returned to the function which calls it. But the array seems to return undefined even tho it isnt.

Example to call the function (shows undefined):

const data = methods.getPunishmentData();
console.log(data);

Function to return the array:

methods.getPunishmentData = function() {
    try {
        mysql.executeQuery(`SELECT * FROM log_punishments LIMIT 50`, function (err, rows, fields) {
            let punishments_data = [];

            rows.forEach(row => {
                const playerPunishment = {
                    time: row['time'].toString(),
                    admin: {
                        name: user.getRpName(user.getPlayerById(methods.parseInt(row['admin']))),
                        id: methods.parseInt(row['admin']),
                    },
                    type: row['type'],
                    player: {
                        name: user.getRpName(user.getPlayerById(methods.parseInt(row['player']))),
                        id: methods.parseInt(row['player']),
                    },
                    reason: row['reason']
                }

                punishments_data.push(playerPunishment);
            });

            return punishments_data;
        });
    }
    catch(ex) {
        methods.error('DB Get Punishments', ex);
    }
};

What could cause this issue? I would appreciate any kind of suggestions.

I was expecting the code to return a array, which has the following structure:

[
  {
    time: 'Thu Apr 13 2023 23:42:47 GMT+0200 (GMT+02:00)',
    admin: { name: 'Danuh Sus', id: 105 },
    type: 'test',
    player: { name: 'Danuh Sus', id: 105 },
    reason: 'test2'
  },
  {
    time: 'Thu Apr 13 2023 23:42:48 GMT+0200 (GMT+02:00)',
    admin: { name: 'Danuh Sus', id: 105 },
    type: 'test',
    player: { name: 'Danuh Sus', id: 105 },
    reason: 'test2'
  },
  {
    time: 'Thu Apr 13 2023 23:42:49 GMT+0200 (GMT+02:00)',
    admin: { name: 'Danuh Sus', id: 105 },
    type: 'test',
    player: { name: 'Danuh Sus', id: 105 },
    reason: 'test2'
  },
  {
    time: 'Fri Apr 14 2023 00:02:53 GMT+0200 (GMT+02:00)',
    admin: { name: 'Danuh Sus', id: 105 },
    type: 'test',
    player: { name: 'Danuh Sus', id: 105 },
    reason: 'test2'
  }
]

This shows that the code itself works and just returns it wrong. To display this I changed return punishments_data; to console.log(punishments_data);

Danuh xux
  • 1
  • 1
  • 3
    your `executeQuery()` operation is asynchronous, and the returned value is going to be ignored. You'll have to structure your code appropriately. – Pointy Apr 13 '23 at 23:13

1 Answers1

0

As mentioned by Pointy in the comment, the function getPunishmentData is asynchronous.

Lets take a better look.

const data = methods.getPunishmentData();
console.log(data);

Your code calls getPunishmentData, but that code needs to talk to the database, which takes a little time, then you add it to the array and return in, but your code continues to run so in the meanwhile you are asking your code to console.log(data)

It returns undefined because all of the database stuff hasn't been done yet. It is still fetching the data, etc.

You need to wait for the function to finish. It's called promise and the promise either resolves or rejects.

So we need to wait for the promise to fulfill.

methods.getPunishmentData().then(data => {
  console.log(data)
})

In order to understand it better it can be helpful to write out some console logs.

console.log('1. Getting data')
methods.getPunishmentData().then(data => {
  console.log('2. Promise resolved')
  console.log(data)
})
console.log('3. done')

You migh think this will log out

  1. Getting data
  2. Promise resolved
  3. Done

But it will log out Getting data, then it will try to talk to the database (asynchronous function), meanwhile your code will continue to run so it logs out Done and then finally when it has gotten the data from the database it will log out Promise resolved.

So it will look like this:

  1. Getting data
  2. Done
  3. Promise resolved
Bergur
  • 3,962
  • 12
  • 20