等待两个异步完成函数完成,然后再执行下一行代码 [英] wait for two asynchronous completion functions to finish, before executing next line code

查看:56
本文介绍了等待两个异步完成函数完成,然后再执行下一行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个功能: func females_NonChat() func males_NonChat()我想等待它们都完成后再在viewdidload中执行print语句.我需要另一个完成处理程序来完成吗?

I have two functions: func Females_NonChat() and func males_NonChat() I want to wait for both of them to finish before executing the print statement in viewdidload. Do I need another completion handler to accomplish that?

使用的那些函数是firebase完成处理程序,用于从在线数据库中请求信息...

Those functions used are firebase completion handlers for requesting information from the online database...

override func viewDidLoad() {
    super.viewDidLoad()
    func Females_NonChat()
    func males_NonChat()

    print("finished executing both asynchronous functions")
}

func Females_NonChat(){
    Anon_Ref.child("Chatting").child("female").observeSingleEventOfType(.Value, withBlock: {(snapshot) in
        if let FemInChatting = snapshot.value as? [String : String] {
            print("executing")
        }
    })
}

func males_NonChat(){
    Anon_Ref.child("Chatting").child("male").observeSingleEventOfType(.Value, withBlock: {(snapshot) in
        print("executing")
    })
}

推荐答案

通常,您将使用调度组,在每个异步方法之前输入该组,在每个异步方法完成后离开该组,然后设置一个组所有输入"呼叫与相应的离开"呼叫匹配时发出通知:

Generally you'd use a dispatch group, enter the group before each asynchronous method, leave the group upon completion of each asynchronous method, and then set up a group notification when all "enter" calls are matched by corresponding "leave" calls:

override func viewDidLoad() {
    super.viewDidLoad()

    let group = dispatch_group_create()

    dispatch_group_enter(group)
    Females_NonChat() {
        dispatch_group_leave(group)
    }

    dispatch_group_enter(group)
    males_NonChat() {
        dispatch_group_leave(group)
    }

    dispatch_group_notify(group, dispatch_get_main_queue()) { 
        print("finished executing both asynchronous functions")
    }
}

func Females_NonChat(completionHandler: () -> ()) {
    Anon_Ref.child("Chatting").child("female").observeSingleEventOfType(.Value) { snapshot in
        if let FemInChatting = snapshot.value as? [String : String] {
            print("executing")
        }
        completionHandler()
    }
}

func males_NonChat(completionHandler: () -> ()) {
    Anon_Ref.child("Chatting").child("male").observeSingleEventOfType(.Value) { snapshot in
        print("executing")
        completionHandler()
    }
}

这篇关于等待两个异步完成函数完成,然后再执行下一行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆