0

With the help of stackoverflow I figured out how to return a value from an asynchronous function.

But now I'm struggling how to use the return directly in a condition.

Here you can have a look at my code:

function playerExists(n, fn) {
        connection.query('SELECT * FROM dorftrophy.spieler;', function (error, results, fields) {
          if (error) throw error;
            const player = results.map(entry => entry.nr); 
            console.log(n);
            console.log(player);
            console.log(player.includes(Number.parseInt(n)));
            fn(player.includes(Number.parseInt(n)));
        });
    }
    const form = {
        playerNr: {
            q: 'Please enter Player number:',
            error: 'Wrong input...',
            validator: (message, callback) => {
                if(message.text && isNumeric(message.text) && playerExists(message.text, function(exists){return exists})) {
                    callback(true, message.text)
                    return
                }

                callback(false)
            }
        }
    }

Look at the if clause. There is this condition:

playerExists(message.text, function(exists){return exists})

I'm searching for a solution where the return of the function playerExists (returns true or false), has directly an effect to the condition.

I guess something I'm doing wrong... Unfortunately I was not able to find a solution on myself.

Deltahost
  • 107
  • 3
  • 11
  • I don't think you *did* figure out how to return a value from an asynchronous function, because you *can't*. – Pointy Feb 23 '17 at 21:32
  • playerExists(message.text, function(exists){return exists})) but the exists has true or false in it? So I though it should be possible to use inside the condition? Or am I wrong...? – Deltahost Feb 23 '17 at 21:35
  • 2
    You're wrong :) You **cannot** return a useful value from an asynchronous operation like what you've got. Instead, you have to do the work you want to do **inside** that callback function you pass. – Pointy Feb 23 '17 at 21:37
  • The only way to achieve that would be using promises and `await`. – Bergi Feb 25 '17 at 12:54

0 Answers0