0

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

0

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.