Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Firestore get() async/await

can anyone help me to "translate" this example in Typescript with async/await

console.log("start") 
var citiesRef = db.collection('cities');
var allCities = citiesRef.get()
    .then(snapshot => {
        snapshot.forEach(doc => {
            console.log(doc.id, '=>', doc.data().name);
        });
        console.log("end")
    })
    .catch(err => {
        console.log('Error getting documents', err);
    });

I tested some code but i think i do something wrong with the 'forEach' loop.

The result i want in console:

start
Key1 => city1
Key2 => city2
end

Result i get in some of my tests:

start
end
Key1 => city1
Key2 => city2

Thx in advance

like image 391
Kloot Avatar asked Nov 20 '17 21:11

Kloot


1 Answers

Without knowing the types, I assumed base on their usage that they conform to the following interface:

var db: {
    collection(name: 'cities'): {
        get(): Promise<Array<{
            id: string;
            data(): { name: string }
        }>>
    }
};

Given that declaration, an async/await version of the code would be

async function foo() {
    console.log("start")
    var citiesRef = db.collection('cities');
    try {
        var allCitiesSnapShot = await citiesRef.get();
        allCitiesSnapShot.forEach(doc => {
            console.log(doc.id, '=>', doc.data().name);
        });
        console.log("end")
    }
    catch (err) {
        console.log('Error getting documents', err);
    }
}
like image 195
Titian Cernicova-Dragomir Avatar answered Nov 07 '22 14:11

Titian Cernicova-Dragomir