Firebase数据库的怪异异步问题

时间:2018-10-17 20:06:21

标签: javascript json firebase

所以我是异步的新手,这里有一个奇怪的问题。我一直在阅读很多有关它的内容,但似乎无法使其正常工作。当我尝试将Firebase数据放入对象数组时,它显示为一个空数组,但是如果单击它,我会看到一条消息,里面写着:“值刚刚被评估”。我的代码都在.then()内部,如果我在其上使用JSON.stringify,则可以看到该对象的JSON版本,但是如果我在该字符串化的对象上使用JSON.parse,它将返回到空对象。

这是我的代码:

let premiereEtoile = [];
let deuxiemeEtoile = [];
let troisiemeEtoile = [];

let resultats = [];

function joueurExiste(nom) {
return resultats.some(function(el) {
    return el.nom === nom
});
};

db.collection('premiereEtoile').get().then((snapshot) => {
snapshot.docs.forEach(doc => {
    premiereEtoile.push(doc.data().premiere);

});
premiereEtoile.forEach(nom => {
    if (joueurExiste(nom)) {
        let i = resultats.findIndex(x => x.nom == nom);
        resultats[i].points += 3

    }
    else {
        resultats.push({ nom: nom, points: 3})
    };
});



});


db.collection('deuxiemeEtoile').get().then((snapshot) => {
snapshot.docs.forEach(doc => {
    deuxiemeEtoile.push(doc.data().deuxieme);

});
deuxiemeEtoile.forEach(nom => {
    if (joueurExiste(nom)) {
        let i = resultats.findIndex(x => x.nom == nom);
        resultats[i].points += 2

    }
    else {
        resultats.push({ nom: nom, points: 2})
    };
});
});

db.collection('troisiemeEtoile').get().then((snapshot) => {
snapshot.docs.forEach(doc => {
    troisiemeEtoile.push(doc.data().troisieme);

});
troisiemeEtoile.forEach(nom => {
    if (joueurExiste(nom)) {
        let i = resultats.findIndex(x => x.nom == nom);
        resultats[i].points += 1

    }
    else {
        resultats.push({ nom: nom, points: 1})
    };
});
let resultatsJSON = (JSON.stringify(resultats));
console.log(resultatsJSON);
console.log(JSON.parse(resultatsJSON));

});

控制台日志:

[{"nom":"elodie turcotte","points":3},{"nom":"leonie-alain","points":6},{"nom":"alexandre-sacha-simoneau","points":9},{"nom":"sabrina-pariseau","points":6},{"nom":"felix-boudreault","points":3},{"nom":"simon-turcotte","points":4},{"nom":"felix-auger","points":2},{"nom":"alex-martin","points":4},{"nom":"mathieu-grondin","points":2},{"nom":"mathieu-muir","points":1},{"nom":"sandrine-voyer","points":1}]
(11) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

谢谢!

0 个答案:

没有答案