布尔函数在javascript中返回undefined?

时间:2016-05-23 14:54:38

标签: javascript function firebase boolean react-native

我目前正在使用存储在Firebase中的数据来检查用户提交的解决方案是否正确。这涉及当用户按下“提交”按钮时调用函数getSolutionAndCompare。但是,出于某种原因,虽然checkSolution返回getSolutionAndCompare,但当我在getSolutionAndCompare中调用onSubmitPressed时,它会评估为未定义。知道我可能做错了吗?

相关代码:

onSubmitPressed: function() {
    var output = this.getSolutionAndCompare();
    console.log('output ' + output); //this is returning undefined
    if (this.getSolutionAndCompare()) {
        Alert.alert(
            'Correct',
            "Woohoo!"
        );
    }
    else {
        Alert.alert(
            'Incorrect Submission',
            'Try again!',
        );
    }
},

getSolutionAndCompare: function() {
    var databaseSolution;
    solutionsRef.orderByChild('question_id').equalTo(Number(this.props.questionId)).once('value', (snap) => {
        var solution = snap.val();
        for (var key in solution) {
            databaseSolution = solution[key].solution;
        }
        return this.checkSolution(databaseSolution); //checkSolution returns true here
    });

},

checkSolution: function(databaseSolution) {
    if (this.state.submission == databaseSolution) {
        return true;
    }
    else {
        return false;
    }
},

1 个答案:

答案 0 :(得分:3)

getSolutionAndCompare没有return语句,因此返回undefined,因为这是默认值。

(您在getSolutionAndCompare内声明的匿名箭头函数有一个return语句,但看起来asyncronous,因此您无法返回其值。)