typescript Firebase Firestore get() 异步/等待
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47401781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Firebase Firestore get() async/await
提问by Kloot
can anyone help me to "translate" this example in Typescript with async/await
谁能帮我用 async/await 在 Typescript 中“翻译”这个例子
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.
我测试了一些代码,但我认为我在“forEach”循环上做错了。
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
提前谢谢
回答by Titian Cernicova-Dragomir
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/await
代码的一个版本将是
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);
}
}