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

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

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

发布评论

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

>www.elefans.com

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