简体   繁体   English

如何创建一个在Node.js和mysql中未使用的随机数

[英]How to create a random number that unused in node.js and mysql

I try to create a random number with following code 我尝试使用以下代码创建一个随机数

let randomnumber = (Math.random().toString().slice(-8))

And I will check if the mysql table has this random number, if doesn't, this number will be inserted into the table, if do, run the above code again, and check again. 然后,我将检查mysql table是否具有该随机数,如果没有,则将该数字插入表中,如果有,请再次运行以上代码,然后再次检查。 like this 像这样

await mysqlModel.checkNumberExit([randomnumber])
.then(async(results) => {
 if (results.length === 0) {
    //doesn't exist, do something
 } else {
   //exist, repeat until the random number doesn't exist
 }

Here is my question, how can I do this function efficiently, this way I am using is very low efficiency, any ideas? 这是我的问题,我如何才能有效地执行此功能,我使用的这种方式效率很低,有什么想法吗?

You can use a function to generate and check: 您可以使用函数来生成和检查:

function getRandomNumber() {
   let randomnumber = Math.floor(Math.random(1000,9999)*100000000);

    mysqlModel.find({"fieldName":randomnumber})
    .then(res => {
        if(!res) {
            //doesn't exist, do something
        }else{
            getRandomNumber();
        }
    }).catch(err => {
        //err
    });
}

call the function using: 使用以下命令调用函数:

getRandomNumber()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM