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

编程入门 行业动态 更新时间:2024-10-25 16:24:43
本文介绍了如何使用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

本文发布于:2023-10-12 00:11:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483233.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   node   ID   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!