【问题标题】:Firebase Firestore get() async/awaitFirebase Firestore get() 异步/等待
【发布时间】:2018-05-04 05:58:11
【问题描述】:

谁能帮我用 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);
    });

我测试了一些代码,但我认为我的“forEach”循环有问题。

我在控制台中想要的结果:

start
Key1 => city1
Key2 => city2
end

我在一些测试中得到的结果:

start
end
Key1 => city1
Key2 => city2

提前谢谢

【问题讨论】:

  • snapshot是什么类型?

标签: typescript google-cloud-firestore


【解决方案1】:

在不知道类型的情况下,我根据它们的用法假设它们符合以下接口:

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

鉴于该声明,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);
    }
}

【讨论】:

  • 我想在var allCitiesSnapShot = await citiesRef.get(); 之后返回一个值,我正在控制台中编写它工作正常但无法返回值。
  • 对于这个答案,如果我想等待.onSnapshot() 以上内容需要如何更改?
【解决方案2】:

异步/等待

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 

}

或承诺函数

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");
        }

}

【讨论】:

    猜你喜欢
    • 2020-05-14
    • 2021-04-16
    • 2021-07-12
    • 2019-04-20
    • 2020-10-17
    • 2020-10-20
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多