如何在Node.js的while循环中处理异步操作?

地亚哥

对于Node API,我必须生成一个随机的字母数字键,该键应该是唯一且简短的(我不能同时使用uuid或Mongo ObjectID)。

我认为这种逻辑:

  1. 生成密钥,
  2. 查询MongoDB以获取键的存在
  3. 如果密钥存在,请重复该过程,
  4. 如果密钥不存在,请分配它并响应客户端。

然后,我尝试了:

do {
  key = randomKey(8);
  newGroup.key = key;
  Group.findOne({numberId: key}).then(function (foundGroup) {
    console.log("cb");

    if (! foundGroup) {
      console.log("not found")
      notUnique = false;
    }

  }).catch(function (err) {
    return response.send(500);
  });

} while (notUnique);

但是,只有我是一个无限循环,notUnique永远不会切换到true以防万一,这是针对一个Empy数据库进行测试的。

我怎么能做到呢?

哈桑新

您可以使用异步模块轻松完成此操作:

var async = require('async')

async.forever(
    function(next) {
        key = randomKey(8);

        Group.findOne({numberId: key}).then(function (foundGroup) {
          console.log("cb");

          if (! foundGroup) {
            console.log("not found")
            notUnique = false;
            next(new Error(), key) // break forever loop with empty error message and the key
          }
          else 
            return next() //continue loop

        }).catch(function (err) {
          next(err); //break loop
          return response.send(500);
        });
    },
    function(err, key) {
        if(key){
           newGroup.key = key;
        }

    }
);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章