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

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


当前回答

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

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

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

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

其他回答

你可以使用urid包npm安装urid

import urid from 'urid';

urid(); // qRpky22nKJ4vkbFZ

阅读完整的文档:https://www.npmjs.com/package/urid

// Set the size
urid(8); //ZDJLC0Zq

// Use the character set
urid('num'); // 4629118294212196
urid('alpha'); // ebukmhyiagonmmbm
urid('alphanum'); // nh9glmi1ra83979b

// Use size with character set
urid(12, 'alpha'); // wwfkvpkevhbg

// use custom character set
urid(6, '0123456789ABCDEF'); // EC58F3
urid('0123456789ABCDEF'); // 6C11044E128FB44B

// some more samples
urid()               // t8BUFCUipSEU4Ink
urid(24)             // lHlr1pIzAUAOyn1soU8atLzJ
urid(8, 'num')       // 12509986
urid(8, 'alpha')     // ysapjylo
urid(8, 'alphanum')  // jxecf9ad

// example of all character sets
urid('num')          // 5722278852141945
urid('alpha')        // fzhjrnrkyxralgpl
urid('alphanum')     // l5o4kfnrhr2cj39w
urid('Alpha')        // iLFVgxzzUFqxzZmr
urid('ALPHA')        // ALGFUIJMZJILJCCI
urid('ALPHANUM')     // 8KZYKY6RJWZ89OWH
urid('hex')          // 330f726055e92c51
urid('HEX')          // B3679A52C69723B1

// custom character set
urid('ABCD-')        // ACA-B-DBADCD-DCA

生成加密性强的伪随机数据。size参数是一个数字,表示要生成的字节数。

// Asynchronous
const {
  randomBytes,
} = require('crypto');

randomBytes(256, (err, buf) => {
  if (err) throw err;
  console.log(`${buf.length} bytes of random data: unique random ID ${buf.toString('hex')}`);
});

知道更多

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

(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 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,也没有测试过这个,但基本思想应该保持不变——不要使用繁忙循环,并使用回调。您可能想看一下节点异步包。