2015-06-21 27 views
1

我在下面的代碼中嘗試過,當搜索數據庫時沒有爲該用戶找到任何東西時執行該操作。這是使用twitch-irc庫和twitch-irc-db模塊(Node.js)。Node.js - 爲什麼這個代碼不工作?

db.where('users', {name: user.username}).then(function(result) { 
    if (!result) { 
     console.log('No result lad'); 
    } 
    var cid = result.items[0].cid; 
    console.log(result.items[0].cid); 
    if (!cid) { 
     db.insert('users', {name: user.username, keys: 0}).then(function() { 
      console.log(user.username + ' is new to the stream, generating them a blank database entry.'); 
     }); 
    } 
}); 

出於某種原因,上面的console.log()行實際上都沒有工作。正如你所看到的,我已經嘗試了if(!result)AND if(!cid)的方法,這兩者都不起作用。

回答

0

是否有可能您的查詢由於某種原因失敗並且您沒有跟蹤錯誤?

嘗試添加.fail

db.where('users', {name: user.username}).then(function(result) { 
    if (!result) { 
     console.log('No result lad'); 
    } 
    var cid = result.items[0].cid; 
    console.log(result.items[0].cid); 
    if (!cid) { 
     db.insert('users', {name: user.username, keys: 0}).then(function() { 
      console.log(user.username + ' is new to the stream, generating them a blank database entry.'); 
     }); 
    } 
}).fail(function(err) {console.log(err)}); 
+0

謝謝你很多!我實際上並不知道如何使用.fail來處理這些錯誤,這對所有未來的發展都會有幫助。事實證明,被拋出的錯誤是說,它無法讀取未定義的cid,所以然後我轉向結果...我改變了第一個if語句if(result == undefined)並且沒有做到這一點,所以然後我進一步向下移動鏈,將其更改爲if(result.items [0] == undefined),並且工作正常。我將db.insert和相應的console.log移到了第一個if語句中,並從db.where中刪除了其餘部分。非常感謝好友。 – Keydose