Firebase数据库调用中的数组记录了正确的数据,但长度显示为0

时间:2019-06-01 12:17:18

标签: javascript jquery firebase google-cloud-firestore

我正在调用数据库,并从数组中获取每个映射项,并将它们存储在要返回的数组中。如果我登录到控制台,该数组将显示正确的数据,但是当我尝试引用任何数据并且该数组的长度也为零时,该数组似乎为空。

$(document).ready(function(){
    //This ('click','li') binds all dynamically added shit to respond to click.
    $('ul.hiddentext').on('click','li', function(e){
        $(this).siblings().css('font-weight','normal');
        $(this).css('font-weight','bolder');
        let text = $(this).text();
        currentWorkoutSelected = text;
        var exercises = pullWorkoutTableData(text)
        console.log(exercises.length);
        var workout = new workoutTemplate(text, user, exercises);
        workout.populateTable();

        //Populate the title of the workout based on if its already there or not.
        if($('h4#workoutTitle').length == 0){
            $("table.exerciseList").prepend('<h4 id="workoutTitle">'+ text+ '</h4>');
        }
        else{
            $('h4#workoutTitle').replaceWith('<h4 id="workoutTitle">'+ text+ '</h4>');
        };
    });
});

//Taking the data needed for the workout table from the database.
function pullWorkoutTableData(workoutName){
    var exerciseList = [];
    db.collection('workouts').get().then((snapshot)=>{
        snapshot.docs.forEach(doc => {
            if(doc.data().name === workoutName && doc.data().user.includes(user)){
                doc.data().exercises.forEach(element =>{
                    var exercise = [element.name, element.weight, element.reps];
                    exerciseList.push(exercise);
                });
            };
        });
    });
    console.log(exerciseList);
    this.setState({exerciseList});
    return exerciseList;
};

期望能够调用populateTable函数,但由于数组为空,因此未正确创建对象。

1 个答案:

答案 0 :(得分:1)

问题是db.collection返回一个Promise,并且在您记录该数据时尚不可用。

您可以在这里尝试几件事:

如果只关心React状态,请将设置的状态移到侦听器中

function pullWorkoutTableData(workoutName){
    var exerciseList = [];
    db.collection('workouts').get().then((snapshot)=>{
        snapshot.docs.forEach(doc => {
            if(doc.data().name === workoutName && doc.data().user.includes(user)){
                doc.data().exercises.forEach(element =>{
                    var exercise = [element.name, element.weight, element.reps];
                    exerciseList.push(exercise);
                });
            };
        });
        this.setState({exerciseList}); // <---- HERE
    });

    return exerciseList;
};

您可以做的另一件事是使用async / await函数,但更新状态可能足以满足您的情况了:)

如果浏览器支持。

function pullWorkoutTableData(workoutName){
    var exerciseList = [];
    return db.collection('workouts').get().then((snapshot)=>{
        snapshot.docs.forEach(doc => {
            if(doc.data().name === workoutName && doc.data().user.includes(user)){
                doc.data().exercises.forEach(element =>{
                    var exercise = [element.name, element.weight, element.reps];
                    exerciseList.push(exercise);
                });
            };
        });
        return Promise.resolve({ exerciseList })
    });
};
$(document).ready(async function(){
    //This ('click','li') binds all dynamically added shit to respond to click.
    $('ul.hiddentext').on('click','li', function(e){
        $(this).siblings().css('font-weight','normal');
        $(this).css('font-weight','bolder');
        let text = $(this).text();
        currentWorkoutSelected = text;
        var { exerciseList: exercises } = await pullWorkoutTableData(text)
        console.log(exercises.length);
        var workout = new workoutTemplate(text, user, exercises);
        workout.populateTable();

        //Populate the title of the workout based on if its already there or not.
        if($('h4#workoutTitle').length == 0){
            $("table.exerciseList").prepend('<h4 id="workoutTitle">'+ text+ '</h4>');
        }
        else{
            $('h4#workoutTitle').replaceWith('<h4 id="workoutTitle">'+ text+ '</h4>');
        };
    });
});