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

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

问题描述

 函数generate(count){
var found = false,
_sym ='abcdefghijklmnopqrstuvwxyz1234567890',
str =''
while(!found){
for(var i = 0; i< count; i ++){
str + = _sym [parseInt(Math.random()*(_sym.length ))];
}
base.getID(string,function(err,res){
if(!res.length){
found = true; //如何做? b $ b}
});
}
return str;
}

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



提前感谢

解决方案

自从我使用了node.js以来,已经有一段时间了,但我想我可以帮忙。



首先,在节点中,你只有一个线程,使用回调。你的代码将会发生什么,是 base.getID 查询将被排队等待执行,但循环将无休止地作为一个繁忙的循环运行。



您应该可以使用回调来解决您的问题,如下所示:

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

(var i = 0; i< count; i ++){
str + = _sym [parseInt(Math.random()*(_sym.length)
}
base.getID(str,function(err,res){
if(!res.length){
k(str)//使用延续
} else generate(count,k)//否则,recurse on generate
});
}

使用它这样


$ b $生成(10,function(uniqueId){
//有一个uniqueId
})

我在大约2年内没有对任何节点/ j进行编码,没有测试过,但基本思想应该是 - 不要使用繁忙的循环,并使用回调。您可能需要查看节点异步包。


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?

Thanks in advance.

解决方案

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天全站免登陆