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

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


当前回答

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

其他回答

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

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

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

npm i uniqid

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

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

特点:-

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

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

const crypto = require("crypto");

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

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

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

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

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

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