如何使用 node.js 生成唯一 ID [英] How to generate unique ID with node.js

查看:102
本文介绍了如何使用 node.js 生成唯一 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数生成(计数){var 成立 = 假,_sym = 'abcdefghijklmnopqrstuvwxyz1234567890',str = '';而(!成立){for(var i = 0; i < count; i++) {str += _sym[parseInt(Math.random() * (_sym.length))];}base.getID(string, function(err, res) {如果(!res.length){成立 = 真;//怎么做?}});}返回字符串;}

如何使用数据库查询回调设置变量值?我该怎么做?

解决方案

我已经有一段时间没有使用 node.js,但我想我可以提供帮助.

首先,在 node 中,你只有一个线程并且应该使用回调.您的代码会发生什么,base.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) {如果(!res.length){k(str)//使用延续} else generate(count, k)//否则,递归生成});}

就这样使用

generate(10, function(uniqueId){//有一个唯一标识})

我已经有大约 2 年没有编写任何 node/js 代码了,也没有对此进行过测试,但基本思想应该成立—​​—不要使用忙循环,而要使用回调.您可能想查看节点异步包.

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

How to set a variable value with database query callback? How I can do it?

解决方案

It's been some time since I used node.js, but I think I might be able to help.

Firstly, in node, you only have a single thread and are supposed to use callbacks. What will happen with your code, is that base.getID query will get queued up by for execution, but the while loop will continusouly run as a busy loop pointlessly.

You should be able to solve your issue with a callback as follows:

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

And use it as such

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

I haven't coded any node/js in around 2 years and haven't tested this, but the basic idea should hold – don't use a busy loop, and use callbacks. You might want to have a look at the node async package.

这篇关于如何使用 node.js 生成唯一 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆