Reactjs 为什么在forEach结束之前完成If?

Reactjs 为什么在forEach结束之前完成If?,reactjs,react-native,Reactjs,React Native,这是我的代码,我从firebase获取数据并将其放入数组中,然后我想检查数组大小,但数组大小检查是在我完成填充数组之前完成的 谢谢你的帮助 componentDidMount() { console.log("MyOrder componentDidMount"); this.setState({order:[]}) var user = Firebase.auth().currentUser; db.collection("request") .where("getUid", "==",

这是我的代码,我从firebase获取数据并将其放入数组中,然后我想检查数组大小,但数组大小检查是在我完成填充数组之前完成的 谢谢你的帮助

componentDidMount() {
console.log("MyOrder componentDidMount");
this.setState({order:[]})
var user = Firebase.auth().currentUser;
db.collection("request")
  .where("getUid", "==", user.uid)
  .get()
  .then(querySnapshot => {
    querySnapshot.forEach(doc => {
        db.collection("users").doc(doc.data().postUid).get().then(doc2=>{
            console.log("ggggggggggggggg")
            var a = this.state.order;
            var b=doc.data()
            b.phone=doc2.data().phone
            a.push(b);
            this.setState({ order: a });
        })

    });
    if (this.state.order.length == 0) 
    {
      this.setState({ loading: false });
    } 
    else 
    {
      var size=this.state.order.length
      var arry=[]
      for(let i=size-1;i>=0;i--)
      {
        console.log(i)
        arry.push(this.state.order[i])
      }
      this.setState({ order: arry });
      this.setState({ loading: false });
      this.setState({ c: true });
    }
  })
  .catch(function (error) {
    console.log("Error getting documents: ", error);
  });

}这是因为数组填充发生在异步的API响应的then块中。在执行API响应数组大小代码之前。。。如果你不明白我的解释,请用JavaScript解释一下承诺的概念

解决方案

  • 将数组大小检查代码包装在一个函数中,并调用该函数,然后在块末尾调用该函数
  • 在API响应后,使用async Wait组合进行数组大小检查

  • 这是因为数组填充发生在异步的API响应的then块中。在执行API响应数组大小代码之前。。。如果你不明白我的解释,请用JavaScript解释一下承诺的概念

    解决方案

  • 将数组大小检查代码包装在一个函数中,并调用该函数,然后在块末尾调用该函数
  • 在API响应后,使用async Wait组合进行数组大小检查