gpt4 book ai didi

javascript - 函数的返回值总是未定义且顺序

转载 作者:行者123 更新时间:2023-12-03 09:56:55 24 4
gpt4 key购买 nike

我尝试创建一个生成随机数字的函数,并验证它是否尚未使用,然后返回它。

但是我得到了一个未定义的结果,并且我首先根据该函数中的 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,我也会收到“main() 中函数的结果未定义”,并且在收到错误后,因为“d. id”未定义。

error with a image

我想首先获取console.log(位于函数中),然后获取函数的结果。

你有什么想法吗?谢谢

最佳答案

我修改了您的函数以使用 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;
}

关于javascript - 函数的返回值总是未定义且顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30703128/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com