简体   繁体   中英

Firestore multiple queries

I am new in nodejs, I want to multiple queries from Firestore database in nodejs (cloud functions).

Minimum 1 query, maximum 5 only if data.query[0,1...] is defined.

if(data.query[0] !== undefined)
    {
db.collection('example').doc(data.query[0]).listCollections().then(collections => {
            collections.forEach(collection => {
                console.log('Found subcollection with id:', collection.id);
               allcollections = allcollections + collection.id + '&';
            })
      });
    }

if(data.query[1] !== undefined)
    {
db.collection('example').doc(data.query[1]).listCollections().then(collections => {
            collections.forEach(collection => {
                console.log('Found subcollection with id:', collection.id);
               allcollections = allcollections + collection.id + '&';
            })
      });
    }

... and at the end I return all collections to client.

My problem is each then should return a value, I don't know how to do run all queries and only return results (allcollections) at the end?

Thanks!

You could try to use Promise.all

It would go in the lines:

var queryPromises = [];

if(data.query[0] !== undefined) {
    var promise = db.collection('example').doc(data.query[0]).listCollections();
    queryPromises.push(promise);
}

if(data.query[1] !== undefined) {
    var promise = db.collection('example').doc(data.query[1]).listCollections();
    queryPromises.push(promise);
}

if(data.query[2] !== undefined) {
    var promise = db.collection('example').doc(data.query[2]).listCollections();
    queryPromises.push(promise);
}

if(data.query[3] !== undefined) {
    var promise = db.collection('example').doc(data.query[3]).listCollections();
    queryPromises.push(promise);
}

if(data.query[4] !== undefined) {
    var promise = db.collection('example').doc(data.query[4]).listCollections();
    queryPromises.push(promise);
}

Promise.all(queryPromises).then(results => {
    // results is an array with the result of each one of the promises
    // Do what you have to do
});

Pay attention to this detail from the documentation:

Returned values will be in order of the Promises passed, regardless of completion order.

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