Kunal M
Kunal M

Reputation: 47

How to put async task in while loop?

How do I have a async task inside a while loop I currently have this

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

  }
 myGroup.leave()                                                                                        
}
completion(arr)

    enter code here

this doesnt not work because it just immediatly goes back up to the while loop while skipping the async .getDocuments part

Upvotes: 0

Views: 154

Answers (1)

ProgrammingFreak
ProgrammingFreak

Reputation: 548

You can create a Promise to handle the async part to make the function flow smoothly. When a promise is resolved, the async .getDocuments part has already done fetching the document. And then, my Group may leave with the docs fetched:

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)

Upvotes: 1

Related Questions