Search code examples
javascriptnode.jsnode-mysql

return value from function is always undefined and order


I try to make a function which generate an aleatory number and verify if it doesn't already used, and return it.

But I got a undefined result, and I got in first the result of the function against the console.log which is in this function, whereas it should be the reverse.

// function main()
console.log('The result of the function in the main() is ' + Bank_generateAccountNumber());

// function Bank_generateAccountNumber()
function Bank_generateAccountNumber()
{
    var account_number = Math.floor((Math.random() * 8999) + 1000);

    console.log('Bank_generateAccountNumber trying with this number: ' + account_number); 
    bdd.query('SELECT * FROM bank_accounts WHERE account_number = ?', gm.mysql.escape(account_number), function(e, d, f) 
    {
        if(!d.id) 
        {
            console.log("this number is available ! " + account_number);
            return account_number;
        }

        console.log("this number is already used ! " + account_number);
        Bank_generateAccountNumber();
        return 0;
    });  
}

I'm seeing when I'm writing this, even if i'm not connected to mysql, i got "the result of the function in the main() is undefined", and after got a error because "d.id" is not defined.

error with a image

I want get the console.log (which is in the function) in first, and after get the result of the function.

Do you have any idea? Thank you


Solution

  • I modified your function to use a deferred promise using the Q library. As Naresh Walia wrote in the comments you have more then one library to do so:

    var q = require('q');
    
    Bank_generateAccountNumber().then(function(response) {
      console.log('The result of the function in the main() is ' + response);
    })
    
    function Bank_generateAccountNumber() {
      var response = q.defer();
      var account_number = Math.floor((Math.random() * 8999) + 1000);
    
      console.log('Bank_generateAccountNumber trying with this number: ' + account_number);
      bdd.query('SELECT * FROM bank_accounts WHERE account_number = ?', gm.mysql.escape(account_number), function(e, d, f) {
        if (!d.id) {
          console.log("this number is available ! " + account_number);
          response.resolve(account_number);
        }
    
        console.log("this number is already used ! " + account_number);
        Bank_generateAccountNumber();
      });
    
      return response.promise;
    }