正确打破每个循环的firebase

问题描述 投票:0回答:1

所以我在我的本机应用程序中有一个函数,需要检查用户输入的代码并将其与firebase-realtime-database中的代码进行比较。目前,我正在使用forEach循环遍历db中的代码,并将它们与输入的代码进行比较。问题是,return语句似乎对此代码段没有影响,并且它始终一直运行。我是一个初学者,所以如果有更好的方法,我完全开放。这是有问题的代码:

function checkCode(text) {
   var code = text;
   codesRef.once('value', function(db_snapshot) {
      db_snapshot.forEach(function(code_snapshot) {
      if (code == code_snapshot.val().value) {
         console.log("Authentication Successful!");
           // break; // throws error
           return; // Does not seem to stop the code segment
      }
   })
   console.log("Authentication Failed!"); // This still runs, even on success...
   //AlertIOS.alert("We're Sorry...", "The code you entered was not found in the database! Please contact Mr. Gibson for further assistance.")
   });
}

我的AccessForm.js的代码如下,我对任何建议持开放态度,即使它与forEach问题无关。

DropBox:AccessForm

javascript firebase react-native firebase-realtime-database
1个回答
1
投票

一旦你开始使用Firebase的DataSnapshot.forEach()循环,你就无法中止它。这意味着您必须捕获变量中的检查状态,然后在循环完成后使用它来确定要打印的内容。

所以类似于:

codesRef.once('value', function(db_snapshot) {
  let isUserFound = false
  db_snapshot.forEach(function(code_snapshot) {
    if (code == code_snapshot.val().value) {
      isUserFound = true
    }
  })
  console.log("Authentication " + isUserFound ? "Successful!" : "Failed!");
});

如果您希望从checkCode返回一个值(这是常见的下一步),您可能想要阅读:JavaScript - Firebase value to global variable

© www.soinside.com 2019 - 2024. All rights reserved.