正确打破forEach循环的火力基地

时间:2019-04-21 13:19:33

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

因此,我的React Native应用程序中有一个功能,需要检查用户输入的代码并将其与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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

嗯...我发现这很有用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
}

NB。我对javascript很陌生,但对我有用。