12

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

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Kloot
  • 228
  • 1
  • 2
  • 8

2 Answers2

13

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);
    }
}
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
  • 3
    I want to return a value after `var allCitiesSnapShot = await citiesRef.get();` I m writing in console which working fine but cannot return a value. – Musaddiq Khan Oct 17 '18 at 10:35
  • For this answer if I wanted to await `.onSnapshot()` how would the above need to be changed? – virtualLast May 16 '19 at 15:00
0

async/await

async function  allData_firestore(){ <---async
  var db = firebase.firestore();

var allCities = await  db.collection('cities').get(); //<----await

 for(const doc of allCities.docs){
console.log(doc.id, '=>', doc.data());
  }
 
 return allCities 

}

Or promise function

function allData_firestore(){
     return db.collection('cities').doc('0gUdiWNEHiPMZStV9G').get().then(function (doc) {
            if (doc.exists) return doc.data();
            return Promise.reject("No such document");
        }

}
Balaji
  • 9,657
  • 5
  • 47
  • 47