如何使用数据库查询回调设置变量值?我该怎么做?
解决方案我已经有一段时间没有使用 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
发布评论