Firebase Firestore get()异步/等待 [英] Firebase Firestore get() async/await

查看:77
本文介绍了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()异步/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆