gpt4 book ai didi

javascript - 在 if 条件下调用异步 JS 函数

转载 作者:行者123 更新时间:2023-11-30 07:32:43 24 4
gpt4 key购买 nike

我想生成一个唯一的 token ,所以我必须检查 token 值是否已经存在于 MongoDB 数据库中。如果 token 已经存在,我正在检查 if 条件。虽然在开发模式下我在数据库中只有几个 token ,所以随机值一定会生成不同的东西,但是一旦在生产中,就会有很多 token 。

我的问题是 if 条件是否会等待数据库查询并从下面的 alreadyExists 函数返回输出?或者是异步的,它将向下移动并再次 generateToken()

这是代码,

//Function to check if string already exists
function alreadyExists(val) {
doc.findOne({token: val}).exec(function(err, docObj){
if(!docObj) return 0; //If token not found, send a false
else if (err) return 1; //If error or token, send a false value
else return 1; //If token found, send a true value
});
}

//Function to generate a random token
function generateToken() {
var t = Math.floor(((Math.random() * 9) + 1.111)*1000); //Generates number between 1000 and 9999
if(!alreadyExists(t)) //Check if token not already exists
return t; //Return the token
generateToken(); //Call recursively again until unique token is generated
}

此外,随机代码是否正确?我必须生成实际在 1111 和 9999 之间的数字(不包括范围结束,但包括也可以)

最佳答案

使用 Promise 和新的 await/async 功能来阻止。

//Function to check if string already exists
async function alreadyExists(val) {
return new Promise(function(reject, resolve){
doc.findOne({token: val}).exec(function(err, docObj){
if(!docObj) reject(0); //If token not found, send a false
else if (err) reject(err); //If error or token, send a false value
else resolve(1); //If token found, send a true value
});
})
}

//Function to generate a random token
function generateToken() {
var t = Math.floor(((Math.random() * 9) + 1.111)*1000); //Generates number between 1000 and 9999
if(! await alreadyExists(t)) //Check if token not already exists
return t; //Return the token
generateToken(); //Call recursively again until unique token is generated
}

关于javascript - 在 if 条件下调用异步 JS 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45912058/

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