如何拿到node的id_如何使用node.js生成唯一的ID

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值