如何使用完成处理程序等待Firestore请求的完成 [英] how to use a completion handler to await the completion of a firestore request

查看:42
本文介绍了如何使用完成处理程序等待Firestore请求的完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在慢慢熟悉完成处理程序.如果我要使用完成处理程序,如果我有一个Firestore查询,则需要向后工作,当Firestore查询完成时,我必须使用completion().

I'm slowly getting my head around completion handlers. Kind of working backwards if I have a firestore query if I wanted to use a completion handler i'd have to use completion() when the firestore query finishes.

但是它设置的功能仍然让我感到困惑.

But it's setting up the function that still confuses me.

因此,如果这是一个将闭包作为参数的函数定义:

So if this is a function definition that takes a closure as a parameter:

  func doSomethingAsync(completion: () -> ()) {
  }

我不太了解如何从上面的func定义中了解如何将其实现为诸如firestore查询和请求之类的真实内容.

I don't quite get how to go from the above func definition and implementing it for something real like a firestore query and request.

 query.getDocuments(){ (querySnapshot, err) in

                if let err = err
                {
                    print("Error getting documents: \(err)")
                }
                else
                {
                    if(querySnapshot?.isEmpty)!
                    {


                        print("there's no document")
                        completion()


                    }
                    else
                    {
                        for document in querySnapshot!.documents
                        {

                            completion()

                        }
                    }
                }

            }

谢谢.

所以对于我的例子,我可以做些类似的事情

so for my example could i do something like

func getFirestoreData(userID: String, completion @escaping() -> ()){

//firestore code:

query.getDocuments(){ (querySnapshot, err) in

                    if let err = err
                    {
                        print("executed first")
                        completion()
                    }
                    else
                  .......
                    print("executed first")
                    completion()

       }
}

要调用我正在执行的功能:

To call the function i'm doing:

getFirestoreData(userID: theUserID) {

            print("executes second")

        }

print("executes third") after function execution.

我想发生的事情是编程在继续执行之前要等待完成().

What i'd like to happen is the programming awaits the completion() before continuing to execute.

但是先执行第三次执行",然后执行先执行",然后再执行第二次执行".

But "executes third" happens first, then "executes first", then "executes second".

谢谢

推荐答案

以下是完整示例(使用API​​调用)注意:status变量只是指出服务器响应的关键.(0:来自服务器的错误,1:成功,-1:我的代码有问题)

Here is full example (With API Call) Note that : status variable is just a key to finger out what is response from server (0: error from server, 1: success, -1: something wrong in my code)

 func logout(handlerBack: @escaping (_ error: Error?, _ status:Int?, _ error_message:String?)->())
{

    Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil)
        .responseJSON { respons in
            switch respons.result {
            case .failure(let theError):
                handlerBack(theError, 0, nil)

            case .success(let data):
                let json_data = JSON(data)

                /// if couldn't fetch data
                guard let status = json_data["status"].int else {
                    handlerBack(nil,-1, "can't find status")
                    return
                }

                /// if statuse == 0
                    guard status == 1 else {
                        handlerBack (nil, 0 , json_data["errorDetails"].string)
                        return
                    }

                // that's means everything fine :)
                    handlerBack(nil, 1 , nil)
                }
        }
    }

这是实现它的方法:

        // call func 
  self.logout { (error:error, status:Int, error_message:String) in
            // if status not 1, figure out the error 
        guard status == 1 else {
            // try to find error from server
            guard let error_message = error_message else {
            // else error something else 
                print ("Error at :: \(#function)")
                // don't do anything ..just return 
                return
            }
            self.showMessageToUser(title: error_message, message: "", ch: {})
            return
        }
                   // this part do what ever you want, means every thing allright 
    }

更新:您正在寻找等待单元执行"First"和"Second"的内容

UPDATE : You are looking for something wait unit execute "First" and "Second"

在这种情况下,请使用 DispatchGroup()这是示例:

in this case use DispatchGroup() here is the example :

            var _dispatch_group = DispatchGroup()

        getFirestoreData(userID: theUserID) {

            _dispatch_group.enter()
            print("executes second")


            _dispatch_group.leave()

        }

        _dispatch_group.notify(queue: .main) {
        print("executes third")
        }

输出为:

executes First
executes Second
executes Third

这篇关于如何使用完成处理程序等待Firestore请求的完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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