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

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


当前回答

我想用这个

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

其他回答

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

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

如果您使用v15.6.0+节点,我们可以使用crypt . randomuuid ([options])。完整的文档在这里。

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

简单,基于时间,没有依赖:

(new Date()).getTime().toString(36)

or

Date.now().toString(36)

输出:jzlatihl


加上随机数(感谢@Yaroslav Gaponov的答案)

(new Date()).getTime().toString(36) + Math.random().toString(36).slice(2)

jzlavejjperpituute输出

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

npm i uniqid

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

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

特点:-

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