我尝试创建一个生成随机数的函数,并验证它是否已经使用过,然后将其返回。
但是我得到了一个未定义的结果,我首先得到了函数的结果,该函数对着这个函数中的console.log,而它应该是相反的。
// 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;
});
}
我看到我写这篇文章的时候,即使我没有连接到mysql,我得到了#34; main()中函数的结果是未定义的&#34 ;和之后出错,因为" d.id"没有定义。
我想先获取console.log(在函数中),然后获取函数的结果。
你知道吗? 谢谢答案 0 :(得分:1)
我修改了你的函数以使用Q库来使用延迟的promise。正如Naresh Walia在评论中写道,你有多个图书馆可以这样做:
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;
}