简体   繁体   中英

More easy way for async firestore return function code

I need to make some methods that get information from Firestore and return this data as a variable. For do that I know the firestore get() method it's asynchronous and I need to wait for end for get this result.

Now I'm using code like:

function retornaIDCompetencia(ambit, numCompetencia) {
return db
    .collection('CCBB')
    .where('ambit', '==', ambit)
    .where('num', '==', '' + numCompetencia + '')
    .get()
    .then(function (querySnapshot) {
        var id;
        querySnapshot.forEach(function (doc) {
            id = doc.id;
        });
        return id;
    })
    .catch(function (error) {
        console.log('Error getting documents: ', error);
    });
}

And to execute this fuction I need something like:

var idcompetencia = retornaIDCompetencia(AMBITS.AMBIT_ARTISTIC, 8);
idcompetencia.then((res) => {
    console.log('id => ', res);
});

Is there are a simple way to call this function? Something that doesn't use then() method? Something like calling the function and do anything, waiting the results inside the function and not outside with then() method.

I still have the same query. There are any alternative and simpliest method for call that function asynchronous and fill a variable?

I believe this should work. Be aware that you may have multiple documents returned and the array will contain multiple ids.

async function retornaIDCompetencia(ambit, numCompetencia) {
    return await db
        .collection('CCBB')
        .where('ambit', '==', ambit)
        .where('num', '==', '' + numCompetencia + '')
        .get();
}

var idcompetencia;
var id;

(async () => {
    idcompetencia = await retornaIDCompetencia(AMBITS.AMBIT_ARTISTIC, 8);
    id = idcompetencia.forEach(doc => doc.id).toString();
})();

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