function generate(count) {
    var founded = false,
        _sym = 'abcdefghijklmnopqrstuvwxyz1234567890',
        str = '';
    while(!founded) {
        for(var i = 0; i < count; i++) {
            str += _sym[parseInt(Math.random() * (_sym.length))];
        }
        base.getID(string, function(err, res) {
            if(!res.length) {
                founded = true; // How to do it?
            }
        });
    }
    return str;
}

如何设置一个变量值与数据库查询回调?我该怎么做呢?


当前回答

我正在使用以下,它是工作良好加上没有任何第三方依赖。

const {
  randomBytes
} = require('crypto');

const uid = Math.random().toString(36).slice(2) + randomBytes(8).toString('hex') + new Date().getTime();

其他回答

NPM中使用https://www.npmjs.com/package/uniqid

npm i uniqid

它总是根据当前时间、进程和机器名创建唯一的id。

对于当前时间,ID在单个进程中总是惟一的。 对于进程ID,即使在同一时刻调用,ID也是唯一的 来自多个进程的时间。 对于MAC地址,ID是唯一的,即使在同一时刻调用 来自多台机器和进程的时间。

特点:-

非常快 即使在多个进程和机器上生成唯一的id 同时打电话。 较短的8字节和12字节版本具有较少的唯一性。

更容易,没有额外的模块

Math.random().toString(26).slice(2)

让count = 0; 令previous = 0; const generateUniqueId = () => { const time = new Date().getTime() Count = time > previous ?0:(++计数) Const uid =时间+计数 Previous = uid 返回uid }

纳米机器人能达到你想要的效果。

使用示例:

const { nanoid } = require("nanoid")

console.log(nanoid())
//=> "n340M4XJjATNzrEl5Qvsh"

我想用这个

class GUID { Generate() { const hex = "0123456789ABCDEF"; const model = "xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx"; var str = ""; for (var i = 0; i < model.length; i++) { var rnd = Math.floor(Math.random() * hex.length); str += model[i] == "x" ? hex[rnd] : model[i] ; } return str.toLowerCase(); } } console.log(new GUID().Generate()); console.log(new GUID().Generate()); console.log(new GUID().Generate()); console.log(new GUID().Generate()); console.log(new GUID().Generate());