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();

其他回答

这里是目前解决方案的一个基准,参考纳米基准

import { v4 as uuid4 } from 'uuid'
import benchmark from 'benchmark'
import shortid from 'shortid'

let suite = new benchmark.Suite()

suite
  .add('crypto.randomUUID', () => {
    crypto.randomUUID()
  })
  .add('nanoid', () => {
    nanoid()
  })
  .add('uuid v4', () => {
    uuid4()
  })
  .add("math.random", () => {
    (new Date()).getTime().toString(36) + Math.random().toString(36).slice(2)
  })
  .add('crypto.randomBytes', () => {
    crypto.randomBytes(32).toString('hex')
  })
  .add('shortid', () => {
    shortid()
  })
  .on('cycle', event => {
    let name = event.target.name
    let hz = formatNumber(event.target.hz.toFixed(0)).padStart(10)

    process.stdout.write(`${name}${pico.bold(hz)}${pico.dim(' ops/sec')}\n`)
  })
  .run()

结果是

node ./test/benchmark.js
crypto.randomUUID         13,281,440 ops/sec
nanoid                     3,278,757 ops/sec
uuid v4                    1,117,140 ops/sec
math.random                1,206,105 ops/sec
crypto.randomBytes           280,199 ops/sec
shortid                       30,728 ops/sec

测试env:

2.6 GHz 6Cores Intel酷睿i7 MacOS 节点v16.17.0

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

安装uuid

npm install --save uuid

Uuid被更新,旧的导入

const uuid = require('uuid/v4');

不工作,我们现在应该使用这个导入

const {v4: uuid} = require('uuid');

把它作为一个函数来使用

const  createdPlace = {
    id: uuid(),
    title,
    description,
    location: coordinates,
    address,
    creator
  };

在Node中创建随机32字符字符串的最快方法是使用本地crypto模块:

const crypto = require("crypto");

const id = crypto.randomBytes(16).toString("hex");

console.log(id); // => f9b327e70bbcf42494ccb28b2d98e00e

从14.17.0开始,你现在可以使用内置的加密模块来生成uuid (UUIDv4 flavour):

const { randomUUID } = require('crypto'); // Added in: node v14.17.0

console.log(randomUUID());

// '89rct5ac2-8493-49b0-95d8-de843d90e6ca'

你可以探索更多 https://nodejs.org/api/crypto.html#crypto_crypto_randomuuid_options

注意:密码。randomUUID比uuid快三倍。而且不需要增加额外的依赖。