user2778425
user2778425

Reputation:

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?

Upvotes: 0

Views: 66

Answers (1)

mmason33
mmason33

Reputation: 998

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();
})();

Upvotes: 1

Related Questions