2015-06-26 80 views
0

對於Node API,我必須生成一個隨機的字母數字鍵,這應該是唯一的,並且SHORT(我不能使用uuid或Mongo ObjectID)。如何使用Node.js處理while循環內的異步操作?

我覺得這樣的邏輯:

  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數據庫進行測試的。

我怎麼能實現它?

+0

你能生成很多密鑰來測試嗎?如果是這樣,您可以使用$ in操作符批量查詢它們。你可能會發現比你生成的密鑰更少的對象,然後你只需檢查一個密鑰是否存在,而對應的對象不存在。 – laggingreflex

回答

2

你可以用異步模塊做到這一點很容易:

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; 
     } 

    } 
); 
+2

這可能是最實用的方法。僅供參考,有一個關於未來版本的Javascript(ECMAScript 7)的建議,稱爲異步/等待,可以讓您更簡潔地編寫這個腳本,今天您可以使用它,感謝Babel:https://babeljs.io/docs/advanced /變壓器/其他/異步到發電機/ –

1

既然你已經在使用的承諾,我會做這樣的事情:創建一個遞歸返回一個承諾的功能,創建一個承諾鏈,並且當條件不滿足時最終拋出錯誤。然後你只需要抓住最後的錯誤。

編輯:更新回到這裏的關鍵

function find(){ 
    var key = randomKey(8); 
    return Group.findOne({numberId: key }) 
    .then(function(foundGroup) { 
     if(foundGroup) return find(); // recursion 
     else throw key; 
    }).catch(function(err){ // in case Group.findOne throws 
     throw key; 
    }); 
} 
find().catch(function(key){ 
    return response.send(key); 
}); 

find功能將保持自稱只要遞歸,因爲它使找到一個有效的對象。而且由於它返回一個承諾,它們都將被自動鏈接。

如果並最終在沒有找到該對象時,或者Group.findOne會引發錯誤,則會拋出該鍵。

find().catch將捕獲最終的錯誤,這將是關鍵。