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;
}

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


当前回答

我的5美分:

const crypto = require('crypto');

const generateUuid = () => {
  return [4, 2, 2, 2, 6] // or 8-4-4-4-12 in hex
    .map(group => crypto.randomBytes(group).toString('hex'))
    .join('-');
};

遗憾的是,Pono的字符串缺少连字符,所以它不符合uuid标准,这是我相信大多数人来这里的原因。

> generateUuid();
'143c8862-c212-ccf1-e74e-7c9afa78d871'
> generateUuid();
'4d02d4d6-4c0d-ea6b-849a-208b60bfb62e'

其他回答

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

使用示例:

const { nanoid } = require("nanoid")

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

对我来说,获取唯一id的最简单方法是时间,我在这个例子中使用哈希

const hash = require('object-hash');
const user = { ..., iat: Date.now() }
const user_id = hash(user)

console.log(user_id) // ex. 49686bab1a2276e0b1bd61ccc86f8156

这就是我在任何方面获得唯一标识符的方法。因为在现实世界中,时间是不会重复的。

安装NPM uuid包(来源:https://github.com/uuidjs/uuid):

npm install uuid

并在你的代码中使用它,例如ES6导入:

import { v4 as uuidv4, v6 as uuidv6 } from 'uuid';

uuidv4();
uuidv6();

或者使用CommonJS需要:

const { 
  v1: uuidv1,
  v4: uuidv4,
} = require('uuid');

uuidv1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' 
uuidv4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1' 

For

这里的解决方案是旧的,现在已弃用:https://github.com/uuidjs/uuid#deep-requires-now-deprecated

用这个:

NPM安装uuid

//add these lines to your code
const { v4: uuidv4 } = require('uuid');
var your_uuid = uuidv4();
console.log(your_uuid);

const uniqueId = self.crypto.randomUUID(); console.log(唯一 Id)

Crypto接口的randomUUID()方法用于使用加密安全的随机数生成器生成v4 UUID。 返回一个包含随机生成的36个字符长的v4 UUID的字符串。