Promise.all with Firebase DataSnapshot.forEach

后端 未结 1 995
鱼传尺愫
鱼传尺愫 2020-12-01 12:55

I have a couple of HTML select\'s (dropdowns) that are populated from a Firebase node called \"states\" (see image below). Upon choosing a city, the below function fires an

相关标签:
1条回答
  • 2020-12-01 13:31

    You have to execute the Promise.all after you filled the array with promises, i.e. inside the then callback:

    function loadMeetings(city,state) {
        //$('#meetingsTable').empty();
        return ref.child('states').child(state).child(city).once('value').then(function(snapshot) {
            var reads = [];
    //      ^^^^^^^^^^^^^^
            snapshot.forEach(function(childSnapshot) {
                var id = childSnapshot.key;
                var promise = ref.child('meetings').child(id).once('value').then(function(snap) {
                    // The Promise was fulfilled.
                }, function(error) {
                    // The Promise was rejected.
                    console.error(error);
                });
                reads.push(promise);
            });
            return Promise.all(reads);
    //      ^^^^^^^^^^^^^^^^^
        }, function(error) {
            // The Promise was rejected.
            console.error(error);
        }).then(function(values) { 
            console.log(values); // [snap, snap, snap] 
        });
    }
    
    0 讨论(0)
提交回复
热议问题