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 uniqueId = self.crypto.randomUUID(); console.log(唯一 Id)

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

其他回答

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

我已经有一段时间没有使用node.js了,但我想我可能能帮上忙。

首先,在node中,你只有一个线程,并且应该使用回调。你的代码会发生什么,就是这个基础。getID查询将被排队等待执行,但while循环将继续作为繁忙循环毫无意义地运行。

你应该能够解决你的问题回调如下:

function generate(count, k) {
    var _sym = 'abcdefghijklmnopqrstuvwxyz1234567890',
    var str = '';

    for(var i = 0; i < count; i++) {
        str += _sym[parseInt(Math.random() * (_sym.length))];
    }
    base.getID(str, function(err, res) {
        if(!res.length) {
          k(str)                   // use the continuation
        } else generate(count, k)  // otherwise, recurse on generate
    });
}

并这样使用它

generate(10, function(uniqueId){
  // have a uniqueId
})

我在2年左右没有编写任何node/js,也没有测试过这个,但基本思想应该保持不变——不要使用繁忙循环,并使用回调。您可能想看一下节点异步包。

如果有人需要加密强UUID,也有解决方案。

https://www.npmjs.com/package/generate-safe-id

npm install generate-safe-id

Why not UUIDs? Random UUIDs (UUIDv4) do not have enough entropy to be universally unique (ironic, eh?). Random UUIDs have only 122 bits of entropy, which suggests that a duplicate will occur after only 2^61 IDs. Additionally, some UUIDv4 implementations do not use a cryptographically strong random number generator. This library generates 240-bit IDs using the Node.js crypto RNG, suggesting the first duplicate will occur after generating 2^120 IDs. Based on the current energy production of the human race, this threshold will be impossible to cross for the foreseeable future.

var generateSafeId = require('generate-safe-id');

var id = generateSafeId();
// id == "zVPkWyvgRW-7pSk0iRzEhdnPcnWfMRi-ZcaPxrHA"

我的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'

从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快三倍。而且不需要增加额外的依赖。