0

我希望该函数等待第一个函数首先从 firebase 获取数据,然后执行第二个函数,但事实证明它没有按正确的顺序工作

func getMenuData(){
    getMenu()
    getIngredient()
    getRecipe()
    self.dispatchGroup.notify(queue: .main){
        print("finished download")
    }
}
func getMenu(){
    self.dispatchGroup.enter()
      let menu = self.ref.collection("menu").document("menu1")
      menu.getDocument(source: .cache) { (document, error) in
           if let document = document {
              let menuName = document.get("menuEngName") as! String
              print("MenuName = \(menuName)")

           } else {
               print("Document does not exist in cache")
           }
       }
    self.dispatchGroup.leave()
}
func getIngredient(){
    for n in 1...5 {
       print("getIngre")
    }
}
func getRecipe(){
    for n in 1...5 {
       print("getRecipe")
    }
}

原来在 MenuName 之前已经打印了“完成下载”

结果图像

先感谢您

4

1 回答 1

0

leave行必须完成闭包内

func getMenu() {
    self.dispatchGroup.enter()
    let menu = self.ref.collection("menu").document("menu1")
    menu.getDocument(source: .cache) { (document, error) in
        if let document = document {
           let menuName = document.get("menuEngName") as! String
           print("MenuName = \(menuName)")
        } else {
           print("Document does not exist in cache")
        }
        self.dispatchGroup.leave()
    }
}
于 2020-05-03T15:40:47.783 回答