调用 1 或 2 个异步函数的最佳实践

Best practice calling 1 or 2 async functions

我的博客 post 存储在远程数据库中。用户可以对每个 post 的评论进行评分 and/or。所以我需要触发 1 或 2 个不同的网络请求。但我必须等到他们(或它)完成。

以下情况的最佳做法是什么:

func updateRatingAndComment (){
        if commentTextView.text != "" {
            updateComment()
        }
        if ratingView.rating != 0.0 {
            updateRating()
        }
    }

updateComment()updateRating() 是 Alamofire 调用。

我试过使用调度组但失败了。我正在考虑使用回调,但这对我来说似乎也没有意义。

试试这个:

let group = DispatchGroup() // Controller property

 .....
        if commentTextView.text != "" {
            group.enter()
            updateComment() // self?.group.leave() inside callback
        }
        if ratingView.rating != 0.0 {
            group.enter()
            updateRating() // self?.group.leave() inside callback
        }

        group.notify(queue: .main) { [weak self] in
            // Do something
        }
....