【问题标题】:Properly break a firebase forEach loop正确打破火力基地 forEach 循环
【发布时间】:2019-09-10 23:30:13
【问题描述】:

所以我的 react native 应用程序中有一个函数需要检查用户输入的代码并将其与 firebase-realtime-database 中的代码进行比较。目前,我正在使用 forEach 循环循环浏览数据库中的代码,并将它们与输入的代码进行比较。问题是,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 问题无关。

投递箱:AccessForm

【问题讨论】:

    标签: javascript firebase react-native firebase-realtime-database


    【解决方案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

    【讨论】:

      【解决方案2】:

      嗯...我发现这很有用Short circuit Array.forEach like calling break

      所以你会有

      function checkCode(text) {
          try {
              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
                          throw BreakException; //<-- use this guy here
                      }
                  })
                  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.")
              });
          } catch (e) {
              if (e !== BreakException) throw e;
          }
      
          //continue code
      }
      

      注意。我对 javascript 很陌生,但它对我有用。

      【讨论】:

        猜你喜欢
        • 2017-07-15
        • 1970-01-01
        • 2016-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多