Javascript 正确地断开firebase forEach循环
因此,我的react原生应用程序中有一个功能,需要检查用户输入的代码,并将其与firebase实时数据库中的代码进行比较。目前,我正在使用forEach循环遍历数据库中的代码,并将它们与输入的代码进行比较。问题是,return语句似乎对这个代码段没有任何影响,而且它总是一直运行。我是一个完全的初学者,所以如果有更好的方法,我是完全开放的思想。下面是有问题的代码:Javascript 正确地断开firebase forEach循环,javascript,firebase,react-native,firebase-realtime-database,Javascript,Firebase,React Native,Firebase Realtime Database,因此,我的react原生应用程序中有一个功能,需要检查用户输入的代码,并将其与firebase实时数据库中的代码进行比较。目前,我正在使用forEach循环遍历数据库中的代码,并将它们与输入的代码进行比较。问题是,return语句似乎对这个代码段没有任何影响,而且它总是一直运行。我是一个完全的初学者,所以如果有更好的方法,我是完全开放的思想。下面是有问题的代码: function checkCode(text) { var code = text; codesRef.once('va
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:一旦使用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!");
});
如果您希望从检查code
返回一个值(这是一个常见的下一步),您可能希望已经阅读:好了。。。我觉得这很有用
所以你会
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
}
功能检查代码(文本){
试一试{
var代码=文本;
codesRef.once('value',函数(db\U快照){
db_snapshot.forEach(函数(代码_snapshot){
if(code==code_snapshot.val().value){
log(“身份验证成功!”);
//break;//抛出错误
//return;//似乎没有停止代码段
抛出异常//