How to generate unique ID with node.js

前端 未结 14 1879
感动是毒
感动是毒 2020-12-12 10:17
function generate(count) {
    var founded = false,
        _sym = \'abcdefghijklmnopqrstuvwxyz1234567890\',
        str = \'\';
    while(!founded) {
        for(va         


        
14条回答
  •  猫巷女王i
    2020-12-12 10:55

    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.

提交回复
热议问题