2017-04-13 121 views
3

如何使用異步功能進行同步操作?如何使用異步回調進行同步操作?

class MyClass { 
    static let shared = MyClass() 
    let operationQueue = OperationQueue() 
    let dispatchGroup = DispatchGroup() 

    func request(_ myRequestURL: URL) { 
     operationQueue.addOperation { 
      self.dispatchGroup.enter() 
      // Async function 
      Alamofire.request(myRequestURL).response { response in 
       print(response.request) 
       self.dispatchGroup.leave() 
      } 

      self.dispatchGroup.wait(timeout: .distantFuture) 
     } 
    } 
} 

MyClass.shared.request(A)
MyClass.shared.request(B)
MyClass.shared.request(C)

輸出:C> A> B
預期:A> B> C


我知道有一個完成塊的方法來這樣做。但是請求將被嵌套。

func request(_ myRequestURL: URL, completion: @escaping (_ data: Data?) -> Void) { 
    // Async function 
    Alamofire.request(myRequestURL).response { response in 
     completion(response.data) 
    } 
} 

MyClass.shared.request(A){_在
        MyClass.shared.request(B){_在
                MyClass.shared .request(C){_
               }
       }
}

+0

的可能的複製[鏈的多個Alamofire請求(http://stackoverflow.com/questions/28634995/chain-multiple-alamofire-requests) – kennytm

+1

讓你的隊列串行:'operationQueue.maxConcurrentOperationCount = 1' – shallowThought

+0

是的。它像JavaScript中的[Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)。我如何用GCD以Swifty的方式做? – WeiJay

回答

3

它的工作原理我使用DispatchQueue而不是爲。

class MyClass { 
    static let shared = MyClass() 
    let dispatchQueue = DispatchQueue(label: "ALAMOFIRE_REQUEST") 
    let dispatchGroup = DispatchGroup() 

    func request(_ myRequestURL: URL) { 
     dispatchQueue.async { 
      self.dispatchGroup.enter() 
      // Async function 
      Alamofire.request(myRequestURL).response { response in 
       print(response.request) 
       self.dispatchGroup.leave() 
      } 

      self.dispatchGroup.wait(timeout: .distantFuture) 
     } 
    } 
}