简体   繁体   中英

Return Array undefined with an async function with firestore

I have a function that i want to return filled array with values from firestore bd, but i need to wait for foreach for this array filled correctly.

I try some methods from this website but I can't understand what I'm doing bad.

My function is:

static async assistencia(id) {
    console.log('Get Assistència ' + id);
    let alumnesId = id;
    var assistenciaAlumne = [];

    db.collection('alumnes')
        .doc(alumnesId)
        .collection('assistencia')
        .get()
        .then((assistencia) => {
            const promises = [];
            assistencia.forEach((assistenciaDoc) => {
                assistenciaAlumne.push([assistenciaDoc.id, assistenciaDoc.data().assistencia]);
                promises.push(db.collection('alumnes').doc(alumnesId).collection('assistencia').get());
            });
            return Promise.all(promises);
        })
        .then(function () {
            return assistenciaAlumne;
        })
        .catch((error) => {
            console.log(error);
        });
}

And I call this function with a button with this code:

var array = Alumnes.assistencia('0qSzBxVimwRlurLHNzXp');
    console.log(' array', array);

Yes, Alumnes it's a class.

The basic problem is that this array returns on console:

array 
Promise {<resolved>: undefined}
    __proto__: Promise
    [[PromiseStatus]]: "resolved"
    [[PromiseValue]]: undefined

What I'm doing wrong?

Right now you return a value from the then() , but nobody does anything value. To return it from assistencia you need to bubble up the return value.

return db.collection('alumnes')
  ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM