【问题标题】:How to put async task in while loop?如何将异步任务放入while循环?
【发布时间】:2020-12-03 19:30:39
【问题描述】:

如何在我目前拥有的 while 循环中拥有异步任务

myGroup = DispatchGroup()
while *condition* {
  myGroup.enter()
  query.getDocuments { (blah, blah) in
    arr.append(docs)
     //...

  }
 myGroup.leave()                                                                                        
}
completion(arr)

    enter code here

这不起作用,因为它只是在跳过异步 .getDocuments 部分时立即返回到 while 循环

【问题讨论】:

    标签: ios swift firebase asynchronous google-cloud-firestore


    【解决方案1】:

    您可以创建一个 Promise 来处理异步部分,以使函数顺利进行。当一个承诺被解决时,异步 .getDocuments 部分已经完成了对文档的获取。然后,我的小组可能会带着获取的文档离开:

    myGroup = DispatchGroup()
    while *condition* {
        myGroup.enter();
        var promise = new Promise((resolve, reject) => {
             query.getDocuments { (blah, blah) in
             arr.append(docs)
             //...
             resolve(true);//or resolve(return-some-val-from-promise-if-you-want)
             }
         })
         promise.then(returnedVal => {
             myGroup.leave()       
         })                                                                                 
    }
    completion(arr)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-30
      • 2022-12-16
      • 2015-04-04
      • 1970-01-01
      相关资源
      最近更新 更多