-1

In the following implementation, I have closure inside another closure and want to return the second closure response. func customerAccount() -> Result {} I am stuck.

public func customerAccount(){
  self.loadCurrentAccount { (account) in
   self.fetchData { (result) in
      // wonder how to return result from the parent method
      print(result)
  }
}

func fetchData(completion: @escaping(Result?) -> Void)  {
  guard let context = self.context else { return }
    
  let parameters = Parameters(scopes: scopes)
  context.fetchData(with: parameters) { (response, error) in
    if let error = error {
      completion(nil)
    }
    guard let response = response else {
      return
    }
    completion(response)
  } 
}
casillas
  • 16,351
  • 19
  • 115
  • 215
  • Does this answer your question? [Swift wait for closure thread to finish](https://stackoverflow.com/questions/47041491/swift-wait-for-closure-thread-to-finish) – timbre timbre Sep 11 '20 at 02:29
  • if `fetchData` uses an asynchronous function `context.fetchData`, then it can't synchronously return a value that it hadn't yet obtained. – New Dev Sep 11 '20 at 02:30
  • Possible duplicate of: [Returning data from async call in Swift function](https://stackoverflow.com/questions/25203556/returning-data-from-async-call-in-swift-function) – TylerP Sep 11 '20 at 02:34
  • Question has been modified. – casillas Sep 11 '20 at 02:47

1 Answers1

1

In these situations its best to use a completion block. The completion block will return the async value...

@IBAction func dataButtonClicked(_ sender: Any) {
 fetchData { (res) in
     self.result = res
 }
}

func fetchData(completion: @escaping (Result?) -> Void)  {
  guard let context = self.context else { 
    completion(nil) 
    return
  }
    
  let parameters = Parameters(scopes: scopes)
  context.fetchData(with: parameters) { (response, error) in
    if let error = error {
      completion(nil)
      return
    }
    guard let response = response else {
      completion(nil)
      return
    }
    completion(response)
  } 
}