本文介绍了Firebase Firestore get() 异步/等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谁能帮我用 async/await 在 Typescript 中翻译"这个例子
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);
});
我测试了一些代码,但我认为我的forEach"循环有问题.
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
提前谢谢
推荐答案
在不知道类型的情况下,我根据它们的用法假设它们符合以下接口:
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 }
}>>
}
};
鉴于该声明,代码的 async/await
版本将是
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);
}
}
这篇关于Firebase Firestore get() 异步/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!