Javascript 强制一个then()语句等待另一个语句的完成

Javascript 强制一个then()语句等待另一个语句的完成,javascript,reactjs,firebase,google-cloud-platform,google-cloud-firestore,Javascript,Reactjs,Firebase,Google Cloud Platform,Google Cloud Firestore,我在componentDidMount()方法中使用React并从Firestore数据库获取数据。我有两个then()调用,一个用于数据库中的数据何时可用并可以保存,另一个用于调整状态 componentDidMount() { db.collection("myCollection") .get() .then(function(querySnapshot) { querySnapshot.forEach(function(

我在
componentDidMount()
方法中使用React并从Firestore数据库获取数据。我有两个
then()
调用,一个用于数据库中的数据何时可用并可以保存,另一个用于调整状态

  componentDidMount() {
    db.collection("myCollection")
        .get()
        .then(function(querySnapshot) {
            querySnapshot.forEach(function(doc) {
                // doc.data() is never undefined for query doc snapshots
                console.log(doc.id, " => ", doc.data().field1);
                allData.push(doc.data());
            })
        })
        .then(
          console.log("Setting State"),
          this.setState({
          isLoaded: true,
          items: allData
        }))
        .catch(function(error) {
            console.log("Error getting documents: ", error);
        });

  }
但是,当我运行站点时,它会尝试先设置状态(第二个
then()
语句),而我不希望它在保存数据库数据之前这样做。我不知道如何在DB数据保存后强制进行状态更改

我尝试过的事情:

1) 将状态更改直接放在函数代码后面的first-then()中。这会产生以下错误:

获取文档时出错:TypeError:无法读取未定义的属性“setState”


您忘记在另一个函数中包装设置状态和控制台日志。如果不这样做,您将向then传递两个参数,一个是console.log的结果,另一个是this.setState的结果。这些是您编写的同步调用。

您需要从第一次回调返回承诺。如果不这样做,就没有什么可等待的了。除上述之外,您看到setState错误的原因是因为您使用的是
函数(){}
,而不是
()=>{}
。箭头函数维护它们在其中声明的“this”上下文,而
function(){}
s不这样做。